<span> jQuery .click() 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19393656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:51:05  来源:igfitidea点击:

<span> jQuery .click() not working

javascriptjqueryhtmlcss

提问by Charles Harrison

So, I created a delete "button" in a span, but for some reason I can't get the .click() to fire. Any ideas? I'm new to jQuery and am thinking that it's something obvious. I tested in Chrome and Safari with no luck.

所以,我在一个跨度中创建了一个删除“按钮”,但由于某种原因,我无法触发 .click() 。有任何想法吗?我是 jQuery 的新手,我认为这很明显。我在 Chrome 和 Safari 中进行了测试,但没有成功。

CSS:

CSS:

.delete_button {
    cursor:pointer;
    color: #fff;
    border: 1px solid #FFF;
    border-radius: 15px;
    background: #AAA;
    font-size: 8px;
    line-height: 0px;
    padding: 0px 2px 0px 2px;
}

HTML/PHP:

HTML/PHP:

<span class="delete_button" id="delete_<? echo $some_id; ?>">X</span>

jQuery:

jQuery:

$(document).ready(function() {
    $('.delete_button').click(function() {
            var transaction_id = $(this).attr('id').replace('delete_','');
            alert("Delete transaction #" + transaction_id);
            return false;
        });
});

回答by Tushar Gupta - curioustushar

use .on()

使用.on()

As your span is added dynamically so it is not present at the time DOM ready or page load.

由于您的跨度是动态添加的,因此在 DOM 就绪或页面加载时不存在。

So you have to use Event Delegation

所以你必须使用事件委托

Syntax

句法

$( elements ).on( events, selector, data, handler );

like this

像这样

$(document).on('click','.delete_button',function(){
    // code here
});

or

或者

$('parentElementPresesntAtDOMready').on('click','.delete_button',function(){
   // code here
});

your code becomes

你的代码变成

$(document).ready(function () {
    $(document).on('click', '.delete_button', function () {
        var transaction_id = $(this).attr('id').replace('delete_', '');
        alert("Delete transaction #" + transaction_id);
        return false;
    });
});  

回答by Anton

It seems like the span is dynamically created, you need to use event delegation. Bind it to the closest static parent or document

看起来跨度是动态创建的,您需要使用事件委托。将其绑定到最近的静态父级或文档

$(document).on('click','.delete_button',function(){
   /*Your code*/
});

回答by Igor Nardo

There is a simpler solution for old webkit: set cursor to pointer via CSS for the span. Tested and working on a music web app.

对于旧的 webkit,有一个更简单的解决方案:通过 CSS 将光标设置为跨度的指针。测试并在音乐网络应用程序上工作。