如何使用变量切换多个元素

时间:2013-06-18 12:30:02

标签: jquery

我有一个代码,它从图像或div中获取数据文本属性,并将其显示为不同div中的描述。我正在使用变量来确定文本是否显示。当具有更多元素时,这是一个问题,因为变量由所有可切换元素共享。我希望代码能够处理所有已分配类的div / images但我不知道如何使用变量修复问题。请参阅jsfiddle以更好地了解我的目标。

var toggled = 0;

$("#main > .item").click(
  function () {
    if(toggled == 0){
      var currentext = $(this).data("text");
      $(this).parent("div").children("div.text").text(currentext);
      toggled ++;
    }
    else{
      $(this).parent("div").children("div.text").empty();
      toggled --;
    }
});

3 个答案:

答案 0 :(得分:3)

您可以使用data函数将数字附加到元素:

$("#main > .item").click(
  function () {
    var toggled = $(this).data('toggled')||0;
    if(toggled == 0){
      var currentext = $(this).data("text");
      $(this).parent("div").children("div.text").text(currentext);
      toggled ++;
    }
    else{
      $(this).parent("div").children("div.text").empty();
      toggled --;
    }
    $(this).data('toggled', toggled);
});

Demonstration

答案 1 :(得分:2)

使用

$("#main > .item").click(function () {
    var $this = $(this);
    if($this.data('toggled')){
        $this.parent("div").children("div.text").empty();
        $this.data('toggled', false);
    }
    else{
        var currentext = $this.data("text");
        $this.parent("div").children("div.text").text(currentext);
        $this.data('toggled', true);
    }
});

演示:Fiddle

答案 2 :(得分:0)

试试这个 -

$("#main > .item").click( function () {
    if ($.trim($(this).next('.text').text()) == "") {
        var currentext = $(this).data("text");
        $(this).next('.text').text(currentext);
    } else {
        $(this).next('.text').text("");
    }
});

演示---> http://jsfiddle.net/ws3FQ/5/