在按钮标签上切换文本

7

我有一个显示/隐藏表格行的功能,但现在想更改我的文本。

<script language="javascript" type="text/javascript">

function HideStuff(thisname) {
    tr = document.getElementsByTagName('tr');        
    for (i = 0; i < tr.length; i++) {
        if (tr[i].getAttribute('classname') == 'display:none;') {
            if (tr[i].style.display == 'none' || tr[i].style.display=='block' )  {
                tr[i].style.display = ''; 
            }
            else {
                tr[i].style.display = 'block'; 
            }
        }
    }
}

The html is as follows...

<button id="ShowHide" onclick="HideStuff('hide');>Show/Hide</button>

我想切换“显示/隐藏”文本。有什么想法吗?

4个回答

11
$('#HideShow').click(function() 
{ 
  if ($(this).text() == "Show") 
  { 
     $(this).text("Hide"); 
  } 
  else 
  { 
     $(this).text("Show"); 
  }; 
});

此外,.toggle() 还有一个 .toggle(even,odd) 的功能,使用哪个取决于你,其中一个代码稍微短一些,但可能不够明确。

$('#HideShow').toggle(function()  
  {  
   $(this).text("Hide");  
     HideClick('hide');
  },  
  function()  
  {  
     $(this).text("Show"); 
     HideClick('hide'); 
  }  
);  

注意:您可以在函数中包含任何其他所需的操作,并且您可以通过在其中调用HideClick()函数来消除标记/HTML中的onclick,如我在第二个示例中演示的那样。

作为跟进,并提供一种替代方案,您可以将CSS类添加到您的CSS中。

.hideStuff
{
display:none;
}

接着添加以下内容:

.toggle('.hideStuff');

或者更直接地说:放在适当的位置。

.addClass('.hideStuff');
.removeClass('.hideStuff');

5

使用jQuery可能会像这样:

$('ShowHide').click(function(){
    if ( $('hide').css('display') == 'block' )
        $('ShowHide').val("Hide");
    else
        $('ShowHide').val("Show");
});

我只是凭想象写的,所以你可能需要做一些修改,你可以在这里阅读更多有关css jquery api的信息。而我所做的只是使用匿名函数。


他正在询问如何更改按钮标签内的文本。 - Çağdaş Tekin
那要更改我的答案有多难?我刚才误读了。 - Filip Ekberg
抱歉,我没有考虑到为您编辑它。无论如何,已经取消了踩的操作。 - Çağdaş Tekin

1
我建议使用jQuery,但你也可以使用JavaScript的document.getElementById方法。
在你的函数中:
function HideStuff(thisname) {
    tr = document.getElementsByTagName('tr');
    for (i = 0; i < tr.length; i++) {
        if (tr[i].getAttribute('classname') == 'display:none;') {
            if (tr[i].style.display == 'none' || tr[i].style.display == 'block') {
                tr[i].style.display = 'none';

            }
            else {
                tr[i].style.display = 'block';

            }
        }
    }
    if (document.getElementById("ShowHide").value == "show") {
        document.getElementById("ShowHide").value = "hide";
    }
    else {
        document.getElementById("ShowHide").value = "show";
    }

}

虽然,我可能会在函数调用中传递this而不是文本“hide”。那么你可以像zaph0d所说的那样做。这样会更加简洁。


0

不确定为什么要将thisname传递到JS中,因为目前没有使用它。

如果您将调用更改为:

<button id="ShowHide" onclick="HideStuff(this)">Show</button>

然后在 JavaScript 中,您可以相当容易地更改文本:

if (this.value == 'Show') {
  this.value = 'Hide'
}
else {
  this.value = 'Show';
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接