【问题标题】:Change button onclick单击更改按钮
【发布时间】:2015-01-14 14:03:38
【问题描述】:

在 html 中,我有一个显示文本的按钮和一个隐藏文本的按钮。每个按钮都有指向 js 中特定功能的“onclick”属性。我想在单击按钮时更改“onclick”值,还想更改按钮内的文本(显示/隐藏)。 我不能使用'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>

有人有解决办法吗?

谢谢!

【问题讨论】:

    标签: javascript jquery html django


    【解决方案1】:

    试试这个短代码:

    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>

    【讨论】:

      【解决方案2】:
      <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>
      

      【讨论】:

        【解决方案3】:
        <script>
        
        $(document).ready(function(){
           $('.show_btn').click(function(){
            if($(this).text()=='Show'){
                $(this).text('Hide');
             }
             else if($(this).text()=='Hide'){
                $(this).text('Show');
             }
           });
        });
        </script>
        

        【讨论】:

          【解决方案4】:
          <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>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-09-16
            • 2018-04-13
            • 2011-06-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-02-18
            相关资源
            最近更新 更多