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

时间:2014-07-30 03:20:07

标签: javascript php jquery html ajax

我的代码在jsfiddle上是单向的,在localhost上是一种方式,在上传到我的网站时是另一种方式。我几天来一直在努力解决这个问题。我不知道在这一点上我可以运行什么测试或试验和错误。

这个jsfiddle正如我希望的那样工作。

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

当我将此代码插入到我的项目中,并使用WAMP在localhost上运行时,页面的javascript不起作用。通过jslint运行时,javascript有效。

更奇怪的是,当我将完全相同的文件上传到我的网站时,javascript功能正常,我甚至可以点击观看按钮并渲染表单,但是没有明确的按钮也没有让我回到原始状态。我的cPanel没有收到任何错误。

当我替换

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

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

本地主机的功能与网站功能相同,功能正常,但没有正常工作的按钮。

下面是代码,但是让我告诉你更多有关页面其余部分的信息。我正在使用php。它是一个.php文件,bootstrap已加载并正常工作,jquery已加载,javascript在页面底部运行,而不是标题。在页面的其他位置运行ajax,它在网站上运行,但不在localhost上运行,并且每个都有正确的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>

这是javascript。

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);
});
});

Event binding on dynamically created elements? 这个问题虽然有用,却没有解决我的问题。我相信我的问题与那个问题是分开的。

1 个答案:

答案 0 :(得分:0)

以下仅将事件处理程序绑定到EXISTING 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/

相关问题