简体   繁体   English

在Javascript中将getAttribute与addEventListener一起使用

[英]Using getAttribute with addEventListener in Javascript

In javascript I create some html to display 5 game characters in a div class named 'characters': 在javascript中,我创建了一些html,以在名为'characters'的div类中显示5个游戏角色:

var element = document.getElementsByClassName('characters');
for(var i in characters){
    // build the character list
    element[0].innerHTML += '<div class="char-container"><img 
    src="'+characters[i].img.default+'" alt="'+characters[i].name+'">
    <h2>'+characters[i].name+'</h2><span class="type '+characters[i].type+'">
    </span></div>';
}

In Javascript I add a click event that i want to return the game character name: 在Javascript中,我添加了一个想返回游戏角色名称的click事件:

var element = document.querySelectorAll ('.characters, .char-container');
let index = 0;
console.log ("element "+element.length);
for( index=0; index < element.length; index++ ) {
    clickerFn = function(){
        var attribute = (this).getAttribute('h2');
        alert("Hello World! +name "+attribute);
    }
    element[index].addEventListener('click', clickerFn, false);
} // for

This returns a null :-( 这将返回null :-(

Question: in Javascript how do I use getAttribute to get 'character.name' ( what's contained in 问题:在Javascript中,我该如何使用getAttribute来获取“ character.name”(

Thanks steve 谢谢史蒂夫

You can't. 你不能 h2 is not an attribute . h2 不是属性 <h2> is an element . <h2>是一个元素

this.querySelector('h2').textContent;

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Javascript中使用addEventListener()出现问题 - Issue using addEventListener() in Javascript $(this).getAttribute在使用$ .each XML Javascript时不是函数 - $(this).getAttribute is not a function when using $.each XML Javascript 在使用javascript getAttribute的测试中使用RegExp - use RegExp with test using javascript getAttribute 将此关键字与javascript原型addEventListener一起使用 - using this keyword with javascript prototype addEventListener 尝试使用使用 JavaScript 的 addEventListener 重用按钮 - Trying to reuse a button using addEventListener using JavaScript 纯JavaScript只能使用data-getAttribute进行一次切换来进行比较 - pure javascript toggle only once using data-getAttribute to to compare 无法使用Javascript中的getAttribute()从表中检索数据 - Can't retrieve the data from table using getAttribute() in Javascript 使用 getAttribute 和 innerText 和 Javascript 创建一个新的 href 属性 - Creating a new href attribute using getAttribute & innerText with Javascript 使用jQuery data()vs native javascript getAttribute vs input hidden - Using jQuery data() vs native javascript getAttribute vs input hidden 使用getAttribute从javascript中的[object SVGCircleElement]中检索值 - Retrieving values from [object SVGCircleElement] in javascript using getAttribute
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM