首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取具有多个html元素的var中元素的属性js/jquery

获取具有多个html元素的var中元素的属性js/jquery
EN

Stack Overflow用户
提问于 2018-06-13 06:58:35
回答 1查看 41关注 0票数 1

我有一个包含多个a元素的div

    <div class="vertical-menu">
        <a href="#" data-actiontime="0" class="listItemActive">
        <strong class="time">00:00</strong> || <strong class="action">Action x</strong>
        </a>
        <a href="#" data-actiontime="36" >
        <strong class="time">00:36</strong> || <strong class="action">Action y</strong>
        </a>
</div>

单击时,每个a都会调用函数myClickHandler

例如,当在1'st a中单击时

function myClickHandler(evt)
{

    evt.preventDefault();

    var elemReceived, attrValue, aElem;

    elemReceived = evt.currentTarget;

    console.log(elemReceived); //it outputs the "a" with the childs elements "strong" ... ok
    aElem = $(elemReceived).find('a'); //get only the "a" element
    console.log(aElem); //it outputs "w.fn.init [prevObject: w.fn.init(1)]length: 0prevObject: w.fn.init [a.listItemActive]__proto__: Object(0)

    attrValue =  $(aElem).attr("data-actiontime"); //alse tried with: aElem.getAttribute("data-actiontime"); but still not working
    console.log(attrValue); //it outputs "undefined"!!!!

globalVarY = attrValue ;
        aElem.setAttribute("class", "listItemActive");

    }

如何解决这个问题呢?

编辑1:

function setListItemClickBehaviour()
{
    var aElements;

    aElements = document.querySelectorAll(".vertical-menu a");
                aElements.forEach(function (aElements)
                {
                    aElements.addEventListener("click", myClickHandler);
                });

}//setListItemClickBehaviour
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-13 07:12:57

您可以像我在下面的代码片段中显示的那样阅读该属性:

function myClickHandler(evt) {
  console.log(this.getAttribute('data-actiontime'));
}

function setListItemClickBehaviour() {
  var aElements = document.querySelectorAll(".vertical-menu a");
  aElements.forEach(function(aElements) {
    aElements.addEventListener("click", myClickHandler);
  });

}

setListItemClickBehaviour();
<div class="vertical-menu">
  <a href="#" data-actiontime="0" class="listItemActive">
    <strong class="time">00:00</strong> || <strong class="action">Action x</strong>
  </a>
  <br />
  <a href="#" data-actiontime="36">
    <strong class="time">00:36</strong> || <strong class="action">Action y</strong>
  </a>
</div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50826965

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档