简体   繁体   English

jQuery设置没有元素的onclick事件

[英]Jquery set onclick event without element

I am writing a card list. 我正在写一张卡片清单。
Before I draw a card, the card list is like this: 在刷卡之前,卡列表是这样的:

<div id="cards-div">
    <ul id="cards-list">
    </ul>
</div>

After I draw a card, the card list is like this: 刷卡后,卡列表如下:

<div id="cards-div">
    <ul id="cards-list">
        <li>hello</li>
    </ul>
</div>

How can I add an onclick function receiving the index at the same time : 如何添加一个onclick函数同时接收索引

<div id="cards-div">
    <ul id="cards-list">
        <li onclick="mouseoverCard(index)">hello</li>
    </ul>
</div>

mouseoverCard: function(index) {
    alert(index);
}

Please note that I tried declaring mouseover function using jquery.click() but it only works when the DOM exists. 请注意,我尝试使用jquery.click()声明mouseover函数,但仅在DOM存在时才起作用。 I want to declare function even the DOM is not exist. 我想声明函数,即使DOM不存在。

As I understood, parent <ul> element is static. 据我了解,parent <ul>元素是静态的。 So you may use event delegation : 因此,您可以使用事件委托

$("#cards-list").on("click", "li", function(e) {
    var i = $(this).index();
    // ...
});

A delegated-events approach attaches an event handler to only one element, the #cards-list , and the event only needs to bubble up one level (from the clicked li to ul ): 委托事件方法将事件处理程序仅附加到一个元素#cards-list ,事件仅需要起泡一个级别(从单击的liul ):

$("#cards-list").on("click", "li", function(event){
     alert($(this).index());
});

Reference: .on() 参考: .on()

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM