简体   繁体   English

Javascript变量,增量函数?

[英]Javascript variable, increment function?

I have a problem with the following JavaScript code: 我对以下JavaScript代码有疑问:

$( "#toggleLog-1" ).click(function() {
  $( "#toggled-1" ).slideToggle( "slow" );
});
$( "#toggleLog-2" ).click(function() {
  $( "#toggled-2" ).slideToggle( "slow" );
});
$( "#toggleLog-3" ).click(function() {
  $( "#toggled-3" ).slideToggle( "slow" );
});
/// ... and many other IDs

As you can see, I want to know how to increment the id and compact my code, because I have many IDs in my css file. 如您所见,我想知道如何增加ID并压缩代码,因为CSS文件中有很多ID。 In php I know how I would do this (with a foreach and increment function), but how can I do it in JavaScript? 在php中,我知道我将如何执行此操作(使用foreach和递增函数),但是如何在JavaScript中执行此操作?

Hmm, how about: 嗯,怎么样:

$("[id^=toggleLog]").click(function() {
    var idNum = this.id.split("-")[1];
    $("#toggled-" + idNum).slideToggle("slow");
});

Although all your clickable elements seem to conform to a specific convention with their id attributes, it would be easier and cleaner to give all the clickable elements a specific class, and a data-* attribute specifying a selector for what element to toggle. 尽管您所有可点击的元素似乎都具有其id属性符合特定的约定,但为所有可点击的元素赋予特定的类和data-*属性来指定要切换的元素的选择器会更容易和更清洁。 For example, have this structure: 例如,具有以下结构:

<div class="toggler" data-toggler="#toggled-2"></div>
<div id="toggled-2"></div>

And use this: 并使用:

$(".toggler").on("click", function () {
    var $this = $(this),
        toggler = $this.attr("data-toggler");

    $(toggler).slideToggle("slow");
});

It targets all the clickable elements by the toggler class. 它针对toggler类的所有可单击元素。 In the click handler, it looks at its specific data-toggler attribute, and selects elements by that, calling .slideToggle() on any found. 在点击处理程序中,它查看其特定的data-toggler属性,并通过该属性选择元素,并在找到的任何属性上调用.slideToggle()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM