动态创建元素上的事件绑定问题


Problems with event binding on dynamically created elements

我的代码在jsfiddle上表现为一种方式,在localhost上表现为一种方式,另一种方式上传到我的网站时。这个问题我已经纠结了好几天了。我不知道我现在可以做什么测试或试错。

这个jsfiddle正在按照我的要求工作。

http://jsfiddle.net/2ZLse/10/

当我将此代码插入到我的项目中,并使用WAMP在本地主机上运行它时,该页面的javascript不起作用。当运行jslint时,javascript是有效的。

更奇怪的是,当我将完全相同的文件上传到我的网站时,javascript是有效的,我甚至可以单击watch按钮并呈现表单,但是nevermind按钮并没有将我返回到原始状态。我没有收到任何错误在我的cPanel。

替换

$(document).on('click', '.nevermind', function() {
    $('#imagebox').html(imagebox);
});

        $('.nevermind').click(function(){
    $('#imagebox').html(imagebox);
});

本地主机的功能将与网站功能相同,具有正常的javascript功能,但没有正常的nevermind按钮。

下面是代码,但让我告诉你更多关于页面的其余部分,如果它是相关的。我在用php。它是一个。php文件,bootstrap被加载并工作,jquery被加载,javascript在页面底部运行,而不是页眉。有ajax在页面的其他地方运行,它在网站上工作,但不是本地主机,我有正确的connect.php文件。我认为这与ajax有关。

问题是什么,或者我可以运行哪些测试?

HTML

<div id="inputbox">
<form><button type="button" id="watchcontrol" class="btn btn-default">Watch</button>
</form>
<br>
</div>
                                <!-- images and continued input extension-->
        <!-- imagebox also acts as control panel -->
<div id="imagebox">
ORIGINAL STATE
</div>

var imagebox = 'ORIGINAL STATE';
var watchform =  '<form action="post/watchpost.php" method="post">' + 
'<input type="text" name="watchid" /><br>' + 
'<input type="submit" class="btn btn-default" value="Contribute" />' + 
'</form>' + 
'<br><br><button type="button" class="btn btn-default nevermind">nevermind</button>';
$(document).ready(function(){
                                    //control functionality
$(document).on('click', '.nevermind', function() {
    $('#imagebox').html(imagebox);
});
$('#watchcontrol').click(function(){
    $('#imagebox').html(watchform);
});
});

动态创建元素的事件绑定?这个问题虽然有帮助,但并没有解决我的问题。我认为我的问题和那个问题是两码事。

下面只将事件处理程序绑定到现有的DOM元素:

$('.nevermind').click(function(){
    $('#imagebox').html(imagebox);
});

不包括点击#watchcontrol后附加的内容。

当你每次创建动态元素时(尽管我建议你在从DOM中删除元素之前释放它),下面的方法就可以工作了:

$('#watchcontrol').click(function(){
    $('#imagebox').html(watchform);
    $('.nevermind').click(function(){
      $('#imagebox').html(imagebox);
    });
});
http://jsfiddle.net/2ZLse/11/