0

So here is my javascript code that I am trying to loop in a cycle. Cycle must repeat 156 times for the 156 unique id-s.

$("#w1").click(function ( event ) {
    event.preventDefault();
    $("#q1").hide();
});
$("#w2").click(function ( event ) {
    event.preventDefault();
    $("#q2").hide();
});
$("#w3").click(function ( event ) {
    event.preventDefault();
    $("#q3").hide();
});
...etc

2 Answers 2

2

Use a for loop, and build your selector strings programatically.

Hint: "#q" + 1 is "#q1", etc. Wrap it in a for loop, replace 1 with a variable and you're basically done.

Sign up to request clarification or add additional context in comments.

Comments

1

You mean

for (var i=1;i<=156;i++) {  
  $("#w"+i).click(function ( event ) {
    event.preventDefault();
    $("#q"+i).hide();
  });

If you instead give all w links a class then

$(".wclass").on("click",function(e) {
    e.preventDefault();
    var idx = this.id.substring(1);
    $("#q"+idx).hide();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.