使用复选框在两个不同的标签内容之间切换

Toggle between two different tag contents using checkbox

HTML

<body class="music">
  <pre class="chord">Chords</pre>
  <div class="lyric" style="display: none">Lyrics</div>
  <input class="c" id="event" type="checkbox" checked data-toggle="toggle" data-size="small" width="5px" data-onstyle="info" data-offstyle="info" data-on="Chords" data-off="Lyrics">
</body>

请帮我 jquery 代码。默认只显示前置标签内容。选中复选框后,我只需要显示 div 标签的内容。当复选框未选中时,我希望发生相反的情况,即只显示 pre 标签的内容。

HTML:

<div id="content1">Content 1</div>
<div id="content2">Content 2</div>
<input type="checkbox" checked id="checkbox">

CSS:

#content2 {
    display: none;
}

JS(使用JQuery):

$(function() {
    $('#checkbox').on('click', function() {
        if (!$(this).is(':checked')) {
            $('#content1').hide();
            $('#content2').show();
        } else {
            $('#content1').show();
            $('#content2').hide();
        }
    });
});

如有任何问题,请提出。

你只需要切换显示。我用间距

的 div 替换了 pre 标签

function jsdisplay(){
$(".chord").eq(0).toggle();
$(".lyric").eq(0).toggle();
}
pre{
margin:0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body class="music">
  <pre class="chord">Chords</pre>
  <div class="lyric" style="display: none">Lyrics</div>
  <input class="c" id="event" type="checkbox" checked data-toggle="toggle" data-size="small" width="5px" data-onstyle="info" data-offstyle="info" data-on="Chords" data-off="Lyrics" onchange="jsdisplay()">
</body>

所以,继续之前的评论,这里是您可能想要使用的代码。

$(function(){
  var chord = $(".chord");
  var lyric = $(".lyric");
  var event = $("#event");
  event.on("change", function(){
    chord.toggle();
    lyric.toggle();
  });
})

通过利用 HTML 中的数据属性,更好的方法是根据复选框选择更新 pre 内容

$(function(){
    var selection = $(".selection");
    var event = $("#event");
    event.on("change", function(){
        var content = $(this).is(":checked") ? $(this).data("on") : $(this).data("off");
        selection.text(content);
    });
})
<script 
    src="https://code.jquery.com/jquery-3.5.1.min.js">
</script>
<body class="music">
  <pre class="selection">Chords</pre>
  <input
    class="c"
    id="event"
    type="checkbox"
    checked data-toggle="toggle"
    data-size="small"
    width="5px"
    data-onstyle="info"
    data-offstyle="info"
    data-on="Chords"
    data-off="Lyrics" />
</body>