Javascript 非常简单的jQuery扰流板功能

Javascript 非常简单的jQuery扰流板功能,javascript,jquery,html,Javascript,Jquery,Html,我使用以下代码实现了一个非常简单的jQuery扰流板功能: HTML: <a href="" onclick="return false" class="spoiler" content="spoiled content"> Reveal spoiler </a> $('a.spoiler').click(function(){ $text = "<a href=\"\" onclick=\"return false\" class=\"spoil

我使用以下代码实现了一个非常简单的jQuery扰流板功能:

HTML:

<a href="" onclick="return false" class="spoiler" content="spoiled content">
    Reveal spoiler
</a>
$('a.spoiler').click(function(){
    $text = "<a href=\"\" onclick=\"return false\" class=\"spoiler\" content=\"" + $(this).text() + "\">" + $(this).attr("content") + "</a>"; 
    $(this).replaceWith($text);
});


jQuery/Javascript:

<a href="" onclick="return false" class="spoiler" content="spoiled content">
    Reveal spoiler
</a>
$('a.spoiler').click(function(){
    $text = "<a href=\"\" onclick=\"return false\" class=\"spoiler\" content=\"" + $(this).text() + "\">" + $(this).attr("content") + "</a>"; 
    $(this).replaceWith($text);
});
$('a.spoiler')。单击(函数(){
$text=”“;
$(this).替换为($text);
});

基本上,我只希望扰流板的内容属性与标记之间的文本交换。它适用于第一次单击,但在再次单击时不会调回

我有没有办法以一种无限期交换内容的方式来实现这一点

谢谢

将代码更改为-

$(document).on('click','a.spoiler',function(){
    $text = "<a href=\"\" onclick=\"return false\" class=\"spoiler\" content=\"" + $(this).text() + "\">" + $(this).attr("content") + "</a>"; 
    $(this).replaceWith($text);
});
$(文档).on('click','a.spoiler',function(){
$text=”“;
$(this).替换为($text);
});
如果正在将新HTML注入页面,请使用委派事件附加事件处理程序

编辑-

简单使用

$('a.spoiler').click(function(){
    var text = $(this).text(); 
    var content = $(this).attr("content");
    $(this).text(content).attr("content", text)
});

否则,您需要使用使用委派事件方法,因为您正在使用
replaceWith
,它是绑定事件的删除元素

$(document).on('click','a.spoiler',function(){
    $text = "<a href=\"\" onclick=\"return false\" class=\"spoiler\" content=\"" + $(this).text() + "\">" + $(this).attr("content") + "</a>"; 
    $(this).replaceWith($text);
});
$(文档).on('click','a.spoiler',function(){
$text=”“;
$(this).替换为($text);
});

您可以使用此

$('a.spoiler').click(function () {
    $(this).text(function (_, t) {
        return t.trim() == "Reveal spoiler" ? $(this).attr('content') : "Reveal spoiler";
    });
});

谢谢!成功了!而且比输入字符串连接要简单得多!