无法让.replaceWith()正常工作

时间:2011-11-19 00:41:25

标签: javascript jquery function

我用.toggle()和下面的更长形式尝试了这个。如果我取出.replaceWith的行,它可以正常显示和隐藏#the-form,但是在...#the-form取消隐藏和#show-form正确更改,但是不适用于下一次点击。

谁能看到我做错了什么?

<script type="text/javascript">
    jQuery('#show-form').click(
        function() {
            if (jQuery("#the-form").is(":hidden")) {
                jQuery('#the-form').show('fast');
                jQuery('#show-form').replaceWith('<div id="show-form">Hide Form</div>');
            } else {
                jQuery('#the-form').hide('fast');
                jQuery('#show-form').replaceWith('<div id="show-form">Show Form</div>');
            }
    });
</script>

UPDATE:从引号中删除了反斜杠。

更新2 工作版本:

<script type="text/javascript">
jQuery('#show-form').live('click',
    function() {
        if (jQuery("#the-form").is(":hidden")) {
            jQuery('#show-form').html('Hide Form');
            jQuery('#the-form').show('fast');
        } else {
            jQuery('#show-form').html('Show Form');
            jQuery('#the-form').hide('fast');
        }
});

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

从div id属性中的双引号中删除反斜杠。它们不需要转义,因为字符串已经用单引号封装。

jQuery('#show-form').replaceWith('<div id="show-form">Hide Form</div>');

另外,将replaceWith()移动到show and hide的回调函数。

jQuery('#the-form').show('fast', function(e) {
    jQuery('#show-form').replaceWith('<div id="show-form">Hide Form</div>');
});

然后,您必须将click事件重新附加到#show-form。您可以使用jQuery live()动态重新附加事件。 See about it here

因此,使用html()可能更好。

e.g。

jQuery('#show-form').html('Hide Form');

这样,您就不会删除和读取新的DOM元素,因此原始的onclick事件侦听器保持不变。

答案 1 :(得分:3)

您正在使用点击处理程序,但您需要使用实时点击处理程序,因为您正在重新创建整个#show-form元素。

这应该有效:

jQuery('#show-form').live('click',
        function() {
            if (jQuery("#the-form").is(":hidden")) {
                jQuery('#show-form').replaceWith('<div id="show-form">Hide Form</div>');
                jQuery('#the-form').show('fast');
            } else {
                jQuery('#show-form').replaceWith('<div id="show-form">Show Form</div>');
                jQuery('#the-form').hide('fast');
            }
    });

实时处理程序处理动态创建的元素,例如您正在重新创建的元素。

答案 2 :(得分:2)

转而回答:

为什么不直接使用html函数? jQuery('#show-form')。html('隐藏表单'),反之亦然