通过使用toggle()函数单击带有类toggleIt的

元素,我已经完成了隐藏和显示div元素的操作。 但是点击后如何更改p标签的名称?

例如,我为p标签命名为“隐藏”。点击这个我隐藏了一个div。现在,我还希望将名称更改为“显示”。我该怎么做?

<p class="toggleIt">Hide</p> //want this to change to 'Show' after clicking

$('.toggleIt').click(function(){

     $('#common_fields').toggle();

});
有帮助吗?

解决方案

我认为您打算更改P元素的文本而不是其名称。

<p class="toggleIt">Hide</p> //want this to change to 'Show' after clicking
$('.toggleIt').click(function(){
  $('#common_fields').toggle();
  var thisElem = $(this);
  thisElem.text(thisElem.text() === "Show" ? "Hide" : "Show");
});

其他提示

您需要知道#common_fields元素是否可见或不符合获得正确的“显示”或“隐藏”文本值:

$('.toggleIt').click(function(){
  var $commonFields = $('#common_fields');
      text = $commonFields.is(':visible') ? 'Show' : 'Hide';

  $(this).text(text);
  $commonFields.toggle();
});

请尝试以上代码段此处

$(".toggleIt").text("Show");

确保这是唯一带有<!> quot; toggleIt <!>的<p>标签;或者你需要使用不同的选择器。

根据您在上面发布的代码,您不是要更改名称属性,而是尝试更改元素的文本值/ innerHTML。

这是通过致电:

完成的
$('.toggleIt').click(function(){
     $('#common_fields').toggle().text('Show');
});

如果您确实想要更改p元素的name属性,那么您可以:

$('.toggleIt').click(function(){
     $('#common_fields').toggle().attr('name', 'Show');
});
var toggleString = {
    show:'Show',
    hide:'Hide'
};

$('.toggleIt').toggle(function() {
    $('#common_fields').hide();
    $(this).text( toggleString.show );
}), function() {
    $('#common_fields').show();
    $(this).text( toggleString.hide );
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top