jquery为单独的div切换文本

时间:2018-01-30 12:36:20

标签: jquery

当我点击它时,我有代码切换单个面板的文本,但我需要在单击其他面板时切换文本。这是代码:

$(".subpaneltext").click(function() {
  if ($(this).closest('.mainpanel').find('.morequestions').hasClass("togglequestions")) {
$(this).closest('.mainpanel').find('.morequestions').removeClass("togglequestions");
} else {
$('.morequestions').removeClass("togglequestions");
$(this).closest('.mainpanel').find('.morequestions').addClass("togglequestions");
}
$(this).text(function(i, text) {
return text === "See more questions..." ? "See less questions..." : "See more questions...";
 })
});

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

检查this fiddle您想要的内容。

有很多重构范围,但作为一种快速解决方案,除了使用此代码更改当前文本外 -

$(this).text(function(i, text) {
return text === "See more questions..." ? "See less questions..." : "See more questions...";
 })

我还补充说,这段代码 -

$(".subpaneltext").not($(this)).text(function(i, text) {
    if(text === "See less questions..."){
      return "See more questions...";
    }
    return text;
  });

根据您检查文本的逻辑,将检查其他所有内容,但.notcheck the docs)当前的this)并仅更改已扩展的文本。同样,这可以在很多层面上进行重构!