JQuery click事件在bootstrap模式中不起作用

afa*_*lek 13 javascript jquery bootstrap-modal

我的页面中有这行代码:

<div id='data'>...</div>      
<a id='addMore' href='#'>Add more </a>   
Run Code Online (Sandbox Code Playgroud)

这一行实际上是一个bootstrap模式.我希望当用户点击它时,我想要克隆它上面的div.问题不在于克隆的代码,而是甚至没有引发click事件.在我的.js文件中,我有这个:

$('#addMore').click (...)
Run Code Online (Sandbox Code Playgroud)

省略号用于防止默认和克隆的代码.我试着用警报进行测试.它仍然无法正常工作.我不知道为什么.

我发现如果我onClick='alert(...)在标签中添加它,它就可以了.

有人可以帮忙吗?

这是模态的HTML(如果有人帮助格式化,请不要介意.我知道这是一团糟):

<div id="addEmailModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="addEmailLabel" aria-hidden="true">   
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times; </button> 
        <h3 id="addEmailLabel">Add Email</h3>
    </div>
    <div class="modal-body">
        <div id="emailData">
            <input type="text" placeholder="Name (optional)" class="input-xlarge" />
            <input type="email" placeholder="Email" />
        </div>
        <a id="addMore" href="#">Add more&hellip;</a>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary" id="btnAdd">Add</button>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

小智 17

尝试事件委托 - jQuery的.on()方法.

如果事件不起作用,可能是因为您的标记<a id='addMore' href='#'>Add more </a>是在页面加载后添加的.您可以使用其父容器捕获事件(注意:当页面加载时,父级应该已存在于DOM中).试试这个:

$(document).ready( function () {
    //Search the parent class, id, or tag and then try to find the <a id="addMore"></a>  as a child
    $('.parent #addMore').on('click', function () {
        alert('addMore click event');
    });
    //Try too with the specific tag
    $('a#addMore').on('click', function () {
        alert('addMore click event');
    });
    //And try too with the specific tag
    $('a #addMore').on('click', function () {
        alert('addMore click event');
    });

});
Run Code Online (Sandbox Code Playgroud)


Arn*_*nab 15

$(document).on('click', '#addMore', function(){...});
Run Code Online (Sandbox Code Playgroud)

Modal没有准备好$(document).ready功能.弹出时它就会变好.可能背后的原因(虽然我不确定).它对我有用,这就是我发布答案的原因.


小智 2

我的猜测是您的元素是在jQuery.ready事件发生后添加到页面中的。您的代码在该块中吗?

$( document ).ready( $('#addMore').click (...) )
Run Code Online (Sandbox Code Playgroud)