javascript - jQuery replaceWith 后缺少 CSS 类。怎么修?

标签 javascript jquery css .net

我将这一行添加到 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。但是当再次点击它时;没有预期的效果。

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

最佳答案

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

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

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

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

关于javascript - jQuery replaceWith 后缺少 CSS 类。怎么修?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26203177/

相关文章:

javascript - 为什么当我点击 li 时会触发 ul?

javascript - jQuery 打开文件对话框在 Chrome 和 IE 中多次打开

html - 有没有办法使表单字段和按钮的字体和高度响应?

html - 调整背景图像大小

javascript - 无需重新加载页面如何使用下面的 JavaScript 插入数据

javascript - 逆转功能或效果

javascript - 使用javascript读取.aspx的内容

javascript - 模态背景覆盖的 Bootstrap 模型

javascript - Bootstrap Accordion + x-editable

javascript - ES6 导入 npm 模块