【问题标题】:CSS class is missed after jQuery replaceWith. How to fix?jQuery replaceWith 后缺少 CSS 类。怎么修?
【发布时间】:2014-10-05 13:49:50
【问题描述】:

我将此行添加到 master.cs 页面。

<h4 class="hideAndShow">[ - ] Hide</h4>

在 CSS 文件中:

.hideAndShow
{
    position: fixed;
    top:120px;
    right:420px;
    color: white;
    background-color:green;
}

然后在同一个 master.cs 页面中。

        <script>
            var hideShowBool = true;

            $('.hideAndShow').bind('click', function ()
            {
                if (hideShowBool == true)
                {
                    $(this).replaceWith('<h4 class="hideAndShow">[ + ] Show</h4>');
                    hideShowBool = false;
                } else
                {
                    $(this).replaceWith('<h4 class="hideAndShow">[ - ] Hide</h4>');
                    hideShowBool = true;
                }
            });
        </script>

预期的行为: [ - ] Hide 文本应在 [ + ] Show[ - ] Hide 之间切换。

但是发生的情况是它只响应第一次点击。其中 [ - ] Hide 被替换为 [ + ] Show。但是当再次点击它时;没有预期的效果。

问题出在哪里?以及如何解决?

【问题讨论】:

标签: javascript jquery css .net


【解决方案1】:

这是因为您要替换元素,所以新元素没有绑定任何点击处理程序。您可以使用事件委托技术:

$('#aStaticParentElement').on('click', '.hideAndShow', function () {

或者改变元素的文本内容而不是替换它:

$('.hideAndShow').on('click', function() {
    $(this).text(function(_, currentText) {
        return currentText === '[ + ] Show'
               ? '[ - ] Hide'
               : '[ + ] Show';
    });
});

【讨论】:

    猜你喜欢
    • 2013-05-17
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多