我已经使用以下代码实现了一个真正简单的 jQuery 剧透功能:
HTML:
<a href="" onclick="return false" class="spoiler" content="spoiled content">
Reveal spoiler
</a>
jQuery/Javascript:
$('a.spoiler').click(function(){
$text = "<a href=\"\" onclick=\"return false\" class=\"spoiler\" content=\"" + $(this).text() + "\">" + $(this).attr("content") + "</a>";
$(this).replaceWith($text);
});
基本上,我只希望扰流板的内容属性与标签之间的文本交换。它适用于第一次点击,但是当再次点击时它不会切换回来。
我有什么办法可以无限期地交换内容吗?
谢谢!
最佳答案
简单使用
$('a.spoiler').click(function(){
var text = $(this).text();
var content = $(this).attr("content");
$(this).text(content).attr("content", text)
});
否则,您需要使用Event Delegation使用 .on()委托(delegate)事件方法,因为您正在使用 replaceWith
,它是删除与事件绑定(bind)的元素。
$(document).on('click','a.spoiler',function(){
$text = "<a href=\"\" onclick=\"return false\" class=\"spoiler\" content=\"" + $(this).text() + "\">" + $(this).attr("content") + "</a>";
$(this).replaceWith($text);
});
关于javascript - 非常简单的 jQuery 剧透功能已经成功了一半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25722713/