使用多个html元素js / jquery获取var中元素的属性

时间:2018-06-12 22:58:35

标签: javascript jquery html frontend

我有div个多个a元素。

    <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&#39; 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

1 个答案:

答案 0 :(得分:0)

您可以在下面的代码段中阅读我正在向您展示的属性:

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>