使用父类和无 ID 的 javascript 检测按钮点击



我试图简单地检测html标签的点击。仅当按钮有 ID 时,它才有效,但我的按钮没有 id 或类。

.html

<div class="parent">
<button>Submit</button>
</div>

.JS

document.getElementByClassName('.parent button').onclick = function() {
alert("clicked");
};

使用它,document.querySelector就像 css 选择器一样工作。

document.querySelector('.parent button').onclick = function() {
alert("clicked");
};

您可以将.querySelector()addEventListener一起使用:

document.querySelector('.parent button').addEventListener('click', function() 
{ 
alert("clicked"); 
});
<div class="parent">
<button>Submit</button>
</div>
document.querySelector('.parent > button').addEventListener('click', function() {
alert('Clicked!');
});

你正在使用getElementByClassName并给它一个Css选择器字符串。
因此它返回 null,因为没有带有类 ".parent 按钮" 的元素

请改用querySelector

document.querySelector('.parent button').onclick = function() {
alert("clicked");
};

最新更新