更改按钮 onclick

Change button onclick

在 html 中,我有一个显示文本的按钮和一个隐藏文本的按钮。每个按钮都有 'onclick' 属性,指向 js 中的特定功能。我想在单击按钮时更改 'onclick' 值,还想更改按钮内的文本 (show/hide)。 我不能使用 'triggleClass' 因为我需要使用 'onclick' 属性(它的值改变了因为我使用的是 django) 目前,我有两个用于此操作的按钮,我只想将它们合并为一个按钮。 代码:

<btn id="show_btn_{{forloop.counter}}" onclick="Show({{forloop.counter}})" class="btn show_btn">Show</btn>
<btn id="hide_btn_{{forloop.counter}}" onclick="Hide({{forloop.counter}})" class="btn hide_btn">Hide</btn>

<script>
function Show(pos){

    $('#show_text_'+pos).css('display','block');
    $('#my_text_show_btn_'+pos).prop("disabled", true);

}

function Hide(pos){
    $('#show_text_'+pos).css('display','none');
    $('#my_text_show_btn_'+pos).prop("disabled", false);

}
</script>

有人有解决办法吗?

谢谢!

<btn id="show_btn_{{forloop.counter}}" onclick="ShowHide({{forloop.counter}})" class="btn show_btn">Show</btn>

<script>
function ShowHide(pos){

    if ($('#show_text_'+pos).css('display') !== 'none') { //lets hide
        $('#show_text_'+pos).css('display','none');
        $('#show_btn_'+pos).html("Show");
    } else {
        $('#show_text_'+pos).css('display','block'); 
        $('#show_btn_'+pos).html("Hide");
    }

}

</script>

试试这个短代码:

function ShowHide(id) {
  if ($(id).html() == "Show") {
    $(id).html("Hide");
  } else {
    $(id).html("Show");
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<btn onclick="ShowHide(this);" class="btn show_btn">Show</btn>

<script>

$(document).ready(function(){
   $('.show_btn').click(function(){
    if($(this).text()=='Show'){
        $(this).text('Hide');
     }
     else if($(this).text()=='Hide'){
        $(this).text('Show');
     }
   });
});
</script>
<button  class="btn show_btn" data-attr='Hide'>Show</button>
<script>

$(document).ready(function(){
   $('.show_btn').click(function(){
       var attr =$(this).attr('data-attr');
       var text =$(this).text();
       $(this).text( attr );
       $(this).attr('data-attr', text );
   });
});
</script>