如何减少 jQuery 代码中的冗余?

发布于 2024-07-27 01:10:37 字数 425 浏览 2 评论 0原文

我的 JavaScript 文件的大小变得无法控制,因为我有数百个链接,每个链接都有自己的 jQuery 函数,尽管它们都执行基本相同的任务。

这是一个简短的摘录:

$("#link1").click(function ()
{
  $(".myDiv").hide();
  $("#myDiv1").toggle();
});

$("#link2").click(function ()
{
  $(".myDiv").hide();
  $("#myDiv2").toggle();
});

$("#link3").click(function ()
{
  $(".myDiv").hide();
  $("#myDiv3").toggle();
});

是否有一种方法可以抽象一些逻辑,以便我只有一个函数而不是数百个做同样事情的函数?

The size of my JavaScript file is getting out of hand because I have hundreds of links, and each one has its own jQuery function even though they all peform basically the same task.

Here's a short excerpt:

$("#link1").click(function ()
{
  $(".myDiv").hide();
  $("#myDiv1").toggle();
});

$("#link2").click(function ()
{
  $(".myDiv").hide();
  $("#myDiv2").toggle();
});

$("#link3").click(function ()
{
  $(".myDiv").hide();
  $("#myDiv3").toggle();
});

Would there be a way to abstract some of this logic so that I have only a single function instead of hundreds that do the same thing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

傻比既视感 2024-08-03 01:10:37

您可以向所有执行相同操作的链接添加一个类,并在该类上使用 jQuery 进行操作。

<a href='whatever' id='link_1' class='toggler'>text</a>
<a href='whatever' id='link_2' class='toggler'>text</a>

jQuery 代码将是:

$(".toggler").click( function(){
    // toggle the divs
    var number = $(this).attr("id").split('_')[1];
    $(".myDiv").hide();
    $("#myDiv"+ number).toggle();
});

You can add a class to all the links that do the same thing and act with jQuery on that class.

<a href='whatever' id='link_1' class='toggler'>text</a>
<a href='whatever' id='link_2' class='toggler'>text</a>

jQuery code will be:

$(".toggler").click( function(){
    // toggle the divs
    var number = $(this).attr("id").split('_')[1];
    $(".myDiv").hide();
    $("#myDiv"+ number).toggle();
});
八巷 2024-08-03 01:10:37

我使用的一般方法是使用遍历方法来查找相关元素,而不是使用绝对选择器。 这将允许您将相同的代码应用于配置类似的元素,而无需对 id 的格式等产生任何复杂的依赖关系。正确完成后,它对于标记的微小更改也具有相当的鲁棒性。

例如,假设我有一系列链接,每个链接后面都有一个 div,通过单击该链接可以切换该 div。 每个链接都有一个特定的类,因此可以轻松引用它们。

<a href="#" class="linkClass">Toggle</a>
<div>
     Some content...
</div>

<a href="#" class="linkClass">Toggle</a>
<div>
     Other content
</div>

然后,我将按类查找所有链接,然后使用 next 方法查找关联的 div 并切换其可见性。 请注意,这是一个简单的示例。 您可能还需要使用更复杂的遍历机制并按元素类型或类进行过滤,具体取决于您的具体标记。

$('.linkClass').click( function() {
    $(this).next().toggle();
});

The general approach that I use is to use the traversal methods to find related elements rather than using absolute selectors. This will allow you to apply the same code to elements that are similarly configured without any complicated dependencies on the format of the ids, etc. Done correctly it's also reasonably robust against minor changes to the mark up.

For example, say I have a series of links, each followed by a div that will be toggled by clicking on that link. The links each have a particular class so they can easily be referenced.

<a href="#" class="linkClass">Toggle</a>
<div>
     Some content...
</div>

<a href="#" class="linkClass">Toggle</a>
<div>
     Other content
</div>

I would then find all the links by class, then use the next method to find the associated div and toggle it's visibility. Note that this is a simple example. You may need to use more complicated traversal mechanisms and filter by element type or class, too, depending on your exact mark up.

$('.linkClass').click( function() {
    $(this).next().toggle();
});
安静被遗忘 2024-08-03 01:10:37

将目标 ID 添加到链接的 href 中怎么样?

<a id="link1" href="#myDiv1" class="toggle">Toggle 1</a><br/>
<a id="link2" href="#myDiv2" class="toggle">Toggle 2</a><br/>
<a id="link3" href="#myDiv3" class="toggle">Toggle 3</a><br/>

然后你可以像这样编写一个函数:

$(".toggle").click(function(e) {
    e.preventDefault();
    $(".myDiv").hide();
    $($(this).attr('href')).toggle();
});

或者我使用的另一种方法:

$(".toggle").each(function(i) {
    $(this).click(function(e) {
        e.preventDefault();
        $(".myDiv").hide();
        $(".myDiv:eq("+i+")").toggle();
    });
});

这个方法与 tvanfosson 的想法相同,使用某种 DOM 关系来链接元素,在这种情况下,假设链接元素和div 元素在页面上的顺序相同。

What about adding the ID of your target into the href of the link?

<a id="link1" href="#myDiv1" class="toggle">Toggle 1</a><br/>
<a id="link2" href="#myDiv2" class="toggle">Toggle 2</a><br/>
<a id="link3" href="#myDiv3" class="toggle">Toggle 3</a><br/>

Then you could write a single function like so:

$(".toggle").click(function(e) {
    e.preventDefault();
    $(".myDiv").hide();
    $($(this).attr('href')).toggle();
});

Or another approach I've used:

$(".toggle").each(function(i) {
    $(this).click(function(e) {
        e.preventDefault();
        $(".myDiv").hide();
        $(".myDiv:eq("+i+")").toggle();
    });
});

This one is in the same vein as tvanfosson's idea, using some sort of DOM relationship to link the elements, in this case by assuming that the link elements and the div elements are in the same order on the page.

无所谓啦 2024-08-03 01:10:37

您可以让每次单击调用外部函数并传入数字字符串的参数。

前任:

$("#link1").click(toggle("1"));
$("#link2").click(toggle("2"));

function toggle(number) {
    $(".myDiv").hide();
    $("#myDiv"+number).toggle();
}

You can just have each click call an external function and pass in a parameter for the number string.

Ex:

$("#link1").click(toggle("1"));
$("#link2").click(toggle("2"));

function toggle(number) {
    $(".myDiv").hide();
    $("#myDiv"+number).toggle();
}
标点 2024-08-03 01:10:37
function makeToggler(number) {
    $('#link' + number).click(function() {
        $('.myDiv').hide();
        $('#myDiv' + number).toggle();
    });
}

makeToggler(1);
makeToggler(2);
makeToggler(3);

您可以调整它以满足您的命名标准。

根据您的 div 和链接的结构,有更好的方法来做到这一点。 如果您发布元素的结构,我将向您展示一个。

function makeToggler(number) {
    $('#link' + number).click(function() {
        $('.myDiv').hide();
        $('#myDiv' + number).toggle();
    });
}

makeToggler(1);
makeToggler(2);
makeToggler(3);

You can adapt this to meet your naming standards.

Depending on the structure of your divs and links, there are better ways to do it. If you post the structure of your elements, I'll show you one.

二货你真萌 2024-08-03 01:10:37

我认为这是一个简单的重构,

您可以定义一个函数

function doSomethingTo(thisDiv)
{
   $(".myDiv").hide();
   $(thisDiv).toggle();
}

,然后在需要的地方重用它

$("#link1).click(doSomethingTo(thisDiv));
$("#link2).click(doSomethingTo(thisDiv));

I think this is a simple refactoring

you could define a function as such

function doSomethingTo(thisDiv)
{
   $(".myDiv").hide();
   $(thisDiv).toggle();
}

and then just reuse it where you need it

$("#link1).click(doSomethingTo(thisDiv));
$("#link2).click(doSomethingTo(thisDiv));
攀登最高峰 2024-08-03 01:10:37

基于克雷格的解决方案:

$("#link1, #link2").click(toggle(this));

function toggle(obj) {
    $(".myDiv").hide();
    $("#myDiv" + $(obj).attr("id").replace('link','')).toggle();
}

Building on Craig's solution:

$("#link1, #link2").click(toggle(this));

function toggle(obj) {
    $(".myDiv").hide();
    $("#myDiv" + $(obj).attr("id").replace('link','')).toggle();
}
夏了南城 2024-08-03 01:10:37

我将链接更改为这样(我将 id 重命名为一个数字)

<a href='#test1' id='1' class='link'> ... </a>
<a href='#test2' id='2' class='link'> ... </a>
<a href='#test3' id='3' class='link'> ... </a>

,然后在 js 上:

$(document).ready(function(){
    $('.link').click(function(){
      $('.myDiv').hide();
      var id = $(this).attr('id'); // take the id
      $('#myDiv'+id).toggle(); 
    });
});

I change the link become like this (i rename the id to just a number)

<a href='#test1' id='1' class='link'> ... </a>
<a href='#test2' id='2' class='link'> ... </a>
<a href='#test3' id='3' class='link'> ... </a>

and then on js:

$(document).ready(function(){
    $('.link').click(function(){
      $('.myDiv').hide();
      var id = $(this).attr('id'); // take the id
      $('#myDiv'+id).toggle(); 
    });
});
梦行七里 2024-08-03 01:10:37

将 makeToggle 放入循环中?

function makeToggler(number) {
    $('#link' + number).click(function() {
        $('.myDiv').hide();
        $('#myDiv' + number).toggle();
    });
}

for(i=1;i>=#;i++) {makeToggler(i);}

那么你甚至可以让它为你计算链接,有什么链接吗?:

function countElementsByClass(className){
  var count = 0;
  var o = document.getElementsByTagName("a").className;
  for(var i=0;i<o.length;i+){
      if(o[i].className == "accordion/whatever")
          count ++;
      }

  return count;
}

信用:基于 SLaCKS 解决方案构建

throw your makeToggle into a loop?

function makeToggler(number) {
    $('#link' + number).click(function() {
        $('.myDiv').hide();
        $('#myDiv' + number).toggle();
    });
}

for(i=1;i>=#;i++) {makeToggler(i);}

then you could even have it count your links for you, something link this?:

function countElementsByClass(className){
  var count = 0;
  var o = document.getElementsByTagName("a").className;
  for(var i=0;i<o.length;i+){
      if(o[i].className == "accordion/whatever")
          count ++;
      }

  return count;
}

credit: building on SLaCKS solution

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文