我将这一行添加到 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/