我有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
答案 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>