我目前正在尝试编写一些JavaScript来获取已被单击的类的属性.我知道要以正确的方式执行此操作,我应该使用事件侦听器.我的代码如下:
var classname = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
classname.addEventListener('click', myFunction(), false);
Run Code Online (Sandbox Code Playgroud)
每次我点击其中一个类告诉我属性时,我都希望得到一个警报框,但遗憾的是这不起作用.有人可以帮忙吗?
(注 - 我可以很容易地做到这一点jQuery,但我不喜欢用它)
我想在单击子 SPAN 时阻止父级单击。我试过
e.stopPropagation
and thi way
if (!e) e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
Run Code Online (Sandbox Code Playgroud)
我有像这样的html:
<label for="parent_id"> Some text
<span id="child_id">Click child</span>
</label>
<input id="parent_id" />
Run Code Online (Sandbox Code Playgroud)
父元素的函数
$('#parent_id').click(function (e) { SomeParentCode }
子元素的函数。
$('#child_id').click(function (e) {
e.stopPropagation();
But I what to prevent parent click
SomeChildCode
}
Run Code Online (Sandbox Code Playgroud)