简体   繁体   English

为什么on函数在这里不起作用-jQuery?

[英]why on function is not working here - jquery?

I want to copy the span element inside the id test element. 我想在id test元素内复制span元素。 I know .clone is working properly.But if i use .html like this .click function is not working. 我知道.clone正常工作。但是,如果我使用.html这样的.click功能不起作用。 Where i did mistake. 我做错了。 how can i approach this only using .html() 我怎么只能使用.html()

HTML : HTML:

<div id="test">
    <span class="new">hi</span>    
</div>

<div id="test1"></div>

Script : 剧本:

function testtt (){

    $('#test').on('click','.new',function(){

        alert('hi');

    });

    var rr  = $('#test').html();

    $('#test').append(rr);

}    
testtt();

Code in fiddle 摆弄代码

My understanding of your question is that you want the click handler to apply to the copied span element. 我对您的问题的理解是,您希望单击处理程序应用于复制的span元素。

You need to change the scope of the on click event to cover the cloned element like so: 您需要更改on click事件的范围,以覆盖克隆的元素,如下所示:

HTML: HTML:

<div id="test" class="clickable">
    <span class="new">hi</span> 
</div>
<div id="test1" class="clickable"></div>

JS: JS:

$('div.clickable').on('click','.new',function(){
    alert('hi');    
});

The reason it's not working is because you're cloning the element into a different selector ( #test1 ) but you're only looking at #test to listen for the click event.. 它不起作用的原因是因为您正在将元素克隆到其他选择器( #test1 )中,但是您仅查看#test来监听click事件。

This is how i'd do it: http://jsfiddle.net/ChubbyNinja/6fv4A/1/ (using your two ids) 这就是我的方法: http : //jsfiddle.net/ChubbyNinja/6fv4A/1/ (使用您的两个ID)

Or http://jsfiddle.net/ChubbyNinja/6fv4A/3/ using a class as a selector, as classes can be used multiple times.. 或使用类作为选择器的http://jsfiddle.net/ChubbyNinja/6fv4A/3/ ,因为类可以多次使用。

Copying its html is not the same as cloning it . 复制其html与克隆它是不同的 You can be less specific when applying your listener: 应用监听器时,您可能不太明确:

 $('body').on('click','.new',function(){...

http://jsfiddle.net/6fv4A/4/ http://jsfiddle.net/6fv4A/4/

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

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