简体   繁体   English

当页面使用name属性加载时,模态有效,但不适用于Jquery attr

[英]Modal works when page is loaded with name attribute but doesn't work with Jquery attr

The jquery code below toggles a name attribute to a button when a checkbox is clicked. 单击复选框时,下面的jquery代码将name属性切换到按钮。 When the name attribute is added, clicking the button displays a modal window. 添加名称属性后,单击按钮将显示一个模式窗口。

Here's the problem: When the name attribute is being added by the jquery (I can see it's added in the Elements console), the modal window code doesn't work. 这是问题所在:当jquery添加name属性时(我可以看到它是在Elements控制台中添加的),模态窗口代码不起作用。 However, it works perfectly when I load the page with the name attribute already in it, ie, <button type="button" name="password-modal-show"> instead of <button type="button" name=""> 但是,当我加载已经具有name属性的页面时,它完美地工作,即<button type="button" name="password-modal-show"> instead of <button type="button" name="">

Is there some kind of 'DOM schedule of events' thing that I'm forgetting? 我忘记了某种“事件的DOM时间表”吗?

   $("#tos-sub").change(function() {

            if(this.checked) {

                $('#password-modal-show').attr('name', 'password-modal-show');

            }
            else {
                $('#password-modal-show').attr('name', '');
            }

        });

        $('button[name=password-modal-show]').click(function() {

            $('#password-modal').modal('show');

        });

<input type="checkbox" value="tos-sub" name="tos-sub" id="tos-sub" class="form-left required"/>
<label>
    <span style="font-size: 80%; margin-right: .5em;">I agree to WifiTap&#39;s <a>Terms of Service</a></span>
</label>
<div style="margin-left: 15px;">
    <button type="button" name="" id="password-modal-show" class="btn big-button" role="button">Get wifi!</button>

Your event handler is not being established because at the moment you are setting it there is no button with this name attribute. 您的事件处理程序尚未建立,因为在您设置事件处理程序时,没有带有此名称属性的按钮。 You have to used delegate events or set the click function on checkbox change. 您必须使用委托事件或在复选框更改时设置单击功能。 Here is the fiddle with problem fixed by using delegated event: 这是通过使用委托事件解决问题的方法:

http://jsfiddle.net/LfkzY/ http://jsfiddle.net/LfkzY/

$(document).click(function(e) {
        if(e.target.getAttribute('name')=='password-modal-show') alert('modal');
});

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

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