使用正确的语法创建.each()函数

时间:2015-10-29 19:01:27

标签: javascript jquery html dry

这是一个noob问题,所以我提前道歉。基本上我有一堆这些小代码片段:

$('#botBox').on('click', '#quest11',function(){
    $("#divContent1").hide().html(quest11).fadeIn(500);
});     
$('#botBox').on('click', '#quest12',function(){
    $("#divContent1").hide().html(quest12).fadeIn(500);
});                 
$('#botBox').on('click', '#quest13',function(){
    $("#divContent1").hide().html(quest13).fadeIn(500);
}); 

正如您所看到的那样,它反复使用相同的代码,并且我想创建一个.each函数,而不是拥有一堆冗余代码。

它所指的标记:

               <p id="quest11" class="quest">C'est quoi?</p>
               <p id="quest12" class="quest">Avantages</p>

它所指的字符串:

var quest11 = "blah blah";
var quest12 = "blah blah blah";

等等。

这就是我提出的:

   $(".quest").each(function(){
            $('#botBox').on('click','#' + $(this).attr("id"),function(){
                $("#divContent1").hide().html($(this).attr("id")).fadeIn(500);
            });     
    });

这个问题是.html()输出字面意思是ID作为字符串。换句话说,quest12的输出将是&#34; quest12&#34;而不是&#34;等等等等等等。

在这个例子中,我如何制作它以使quest12被解释为变量quest12而不是字符串?

4 个答案:

答案 0 :(得分:2)

使用

$(".quest").click(function(){
    $("#divContent1").hide().html(window[$(this).attr("id")]).fadeIn(500);
});

$(this).attr("id")只是一个字符串,window[$(this).attr("id")]将返回var $(this).attr("id")的全局值

$(".quest").click()会在类.quest的所有元素上注册click事件,因此您无需使用.each

或者如果var是本地的,请使用eval代替

$(".quest").click(function(){
    $("#divContent1").hide().html(eval[$(this).attr("id")]).fadeIn(500);
});

答案 1 :(得分:1)

您不需要使用.each。您可以将处理程序直接绑定到所有元素。然后,要获取元素的ID,您可以使用this.id

不应使用全局变量quest11quest12,而应将它们作为对象的属性:

var questions = {
    quest11: "blah blah",
    quest12: "blah blah blah"
};


$("#botBox").on("click", "p", function() {
    $("#divContent1").hide().html(questions[this.id]).fadeIn(500);
});

答案 2 :(得分:1)

首先创建一个对象来保存不同的文本:

var quests = {
  quest11 : "blah blah",
  quest12 : "blah blah blah"
}

然后使用'[id^=quest]'&#34;属性 - 开始 - 用&#34;选择器将所有quest元素委托给botBox

然后,您只需使用this.id获取所点击任务的ID,并将其用作quests对象的键。

// All quest elements ----v---------v
$('#botBox').on('click', '[id^=quest]', function() {
    $("#divContent1").hide().html(quests[this.id]).fadeIn(500);
}); // Use the ID of the element --------^-----^

答案 3 :(得分:0)

$("#divContent1").hide().html(window[this.id]).fadeIn(500);

全局变量绑定到window对象

(假设var questXX变量是全局变量)