jQuery提醒onclick on元素的子对象? [英] jQuery alert onclick on element's child?

查看:81
本文介绍了jQuery提醒onclick on元素的子对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码在特定元素上显示警报:

I'm using this code to display an alert on a certain element:

$("#resultsBox").click(function (event) {
    console.log('a');
    });

我只想在单击"#resultsBox"中的"li"元素时显示警报.

I want to display an alert only when you click on 'li' elements inside '#resultsBox'.

我正在尝试这样做:

$("#resultsBox li").click(function (event) {
    console.log('a');
    });

这是元素的#resultsBox结构:

This is the element's #resultsBox structure:

<div id="resultsBox">
  <ul>
    <li></li>
    <li></li>
  </ul>
</div>

这怎么办?

推荐答案

当您将事件处理程序与.click()绑定时,它适用于当时与选择器匹配的任何元素,而不适用于元素后来动态添加.

When you bind an event handler with .click() it applies to any elements that matched your selector at that moment, not to elements later added dynamically.

鉴于您的div被称为"resultsBox",假设您实际上是在向其动态添加内容以显示其他操作的结果似乎是合理的,在这种情况下,您需要使用委托的事件处理程序:

Given your div is called "resultsBox", it seems reasonable to assume you are actually adding things to it dynamically to display the results of some other operation, in which case you need to use a delegated event handler:

$("#resultsBox").on("click", "li", function (event) {
    console.log('a');
});

.on()方法的这种语法将处理程序绑定到"#resultsBox",但随后当单击发生时,jQuery会检查它是否在与第二个参数中的"li"选择器匹配的子元素上-如果是,它将调用您的函数,否则不调用.

This syntax of the .on() method binds a handler to "#resultsBox", but then when the click occurs jQuery checks whether it was on a child element that matches the "li" selector in the second parameter - if so it calls your function, otherwise not.

这篇关于jQuery提醒onclick on元素的子对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆