2014-02-23 19 views
0

枝我有不同的頁面加載到相同的iframe,所以我有這些功能如何使一個函數加載各種ifram?

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

我怎樣才能讓中庸之道一個函數,以便該函數加載"page"+numid+".html"

回答

0

使用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"); 
}); 

或者

您可以使用Attribute Starts With Selector [name^="value"],雖然我不建議

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

非常感謝! – user3334919

+0

@ user3334919,很高興我能幫忙:) – Satpal

0

您可以使用屬性選擇[attribute='value']用於選擇帶ID的元素,選擇ID從a開始使用[id^='a']
使用slice()獲得數

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

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

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


.match(/\d+$/)[0]從ID獲得數

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

$("[id^=a]") - >所有元素開頭的ID a

相關問題