简体   繁体   中英

How to combine different css class selectors into one javascript line?

How can this code be simplified into one line (js statement)?

     <script>$(".div2").click(function() {window.location = $(this).find("a").attr("href"); return false;});</script>
     <script>$(".div3").click(function() {window.location = $(this).find("a").attr("href"); return false;});</script>
     <script>$(".div4").click(function() {window.location = $(this).find("a").attr("href"); return false;});</script>
     <script>$(".div5").click(function() {window.location = $(this).find("a").attr("href"); return false;});</script>
     <script>$(".div6").click(function() {window.location = $(this).find("a").attr("href"); return false;});</script>
     <script>$(".div7").click(function() {window.location = $(this).find("a").attr("href"); return false;});</script>
     <script>$(".div8").click(function() {window.location = $(this).find("a").attr("href"); return false;});</script>
     <script>$(".div9").click(function() {window.location = $(this).find("a").attr("href"); return false;});</script>

You can short it down to something like this:

$(".div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9").click(function() {
  window.location = $(this).find("a").attr("href");
  return false;
});

Also there is no need to use multiple <script> tags, 1 is enought.

Two answers:

Selector group

You can use a selector group :

$(".div2, .div3, .div4, .div5, .div6, .div7, .div8, .div9")..click(function() {
    window.location = $(this).find("a").attr("href");
    return false;
});

A selector group is a series of selectors with commas in-between. It selects elements matching any of the selectors in the group.

Event delegation

Rather than adding a handler to all of those divs, you could add one to document that only takes action if the click passed through one of those divs:

$(document).on("click", ".div2, .div3, .div4, .div5, .div6, .div7, .div8, .div9", function() {
    window.location = $(this).find("a").attr("href");
    return false;
});

Even if you had multiple statements, there's no reason you couldn't put them in a single script :

<script>
doThis();
doThat();
doTheOther();
</script>

add a common class to elements, as follows.

<div class="div2 my-class"> ... </div>
<div class="div3 my-class"> ... </div>
<div class="div3 my-class"> ... </div>
<div class="div4 my-class"> ... </div>
<div class="div5 my-class"> ... </div>
<div class="div6 my-class"> ... </div>
<div class="div7 my-class"> ... </div>
<div class="div8 my-class"> ... </div>

add the event listener to that common class

$(".my-class").click(function() {
  window.location = $(this).find("a").attr("href");
  return false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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