Question

Hie I have various pages to load to the same iframe, so I have these functions

$("#a1").click(function () { 
      $("#frame").attr("src", "page1.html");
});
$("#a2").click(function () { 
      $("#frame").attr("src", "page2.html");
});
$("#a3").click(function () { 
      $("#frame").attr("src", "page3.html");
});

How can I make juste one function in order that the function load "page"+numid+".html"

Was it helpful?

Solution

Use Multiple Selector ("selector1, selector2, selectorN")

$("#a1, #a2, #a3").click(function () { 
     var num = this.id.match(/\d+/)[0]; //Extract number from ID
     $("#frame").attr("src", "page"+num +".html");
});

Or

You can use Attribute Starts With Selector [name^="value"], Although I don't recommend

$("[id^=a]").click(function () { 
     var num = this.id.match(/\d+/)[0]; //Extract number from ID
     $("#frame").attr("src", "page"+num +".html");
});

OTHER TIPS

Attribute Starts With Selector [name^="value"]

$("[id^=a]").click(function () { 
      $("#frame").attr("src", "page"+this.id.replace('a')+".html");
});


or

.match(/\d+$/)[0] to get number from the id

$("[id^=a]").click(function () { 
      $("#frame").attr("src", "page"+this.id.match(/\d+$/)[0]+".html");
});

$("[id^=a]") --> all elements starting with id a

You can use attribute selector [attribute='value'] for selecting elements with id , to select id starting with a use [id^='a'] .
Use slice() to get the number

$("[id^=a]").click(function () { 
      $("#frame").attr("src", "page" + this.id.slice(1) + ".html/");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top