2014-04-05 33 views
0

在下面你的代碼可以看到我一遍又一遍地只是改變了ID選擇運行的代碼塊...如何申請一個jQuery單擊事件到多個ID的

有沒有更好的方式來緊縮此下降到1個小塊,只需更改#line-1-font,以便號碼可以是任何數字?

$("body").on("click", "#line-1-font", function(event) { 
    $('<link>') 
     .appendTo($('head')) 
     .attr({type : 'text/css', rel : 'stylesheet'}) 
     .attr('href', 'fonts/'+$(this).val()+'-font.css'); 
    $(this).prev().css("font-family", $(this).val()); 
}); 

//

// Change FONTS 
$("body").on("click", "#line-1-font", function(event) { 
    $('<link>') 
     .appendTo($('head')) 
     .attr({type : 'text/css', rel : 'stylesheet'}) 
     .attr('href', 'fonts/'+$(this).val()+'-font.css'); 
    $(this).prev().css("font-family", $(this).val()); 
}); 

$("body").on("click", "#line-2-font", function(event) { 
    $('<link>') 
     .appendTo($('head')) 
     .attr({type : 'text/css', rel : 'stylesheet'}) 
     .attr('href', 'fonts/'+$(this).val()+'-font.css'); 
    $(this).prev().css("font-family", $(this).val()); 
}); 

$("body").on("click", "#line-3-font", function(event) { 
    $('<link>') 
     .appendTo($('head')) 
     .attr({type : 'text/css', rel : 'stylesheet'}) 
     .attr('href', 'fonts/'+$(this).val()+'-font.css'); 
    $(this).prev().css("font-family", $(this).val()); 
}); 

$("body").on("click", "#line-4-font", function(event) { 
    $('<link>') 
     .appendTo($('head')) 
     .attr({type : 'text/css', rel : 'stylesheet'}) 
     .attr('href', 'fonts/'+$(this).val()+'-font.css'); 
    $(this).prev().css("font-family", $(this).val()); 
}); 

$("body").on("click", "#line-5-font", function(event) { 
    $('<link>') 
     .appendTo($('head')) 
     .attr({type : 'text/css', rel : 'stylesheet'}) 
     .attr('href', 'fonts/'+$(this).val()+'-font.css'); 
    $(this).prev().css("font-family", $(this).val()); 
}); 

$("body").on("click", "#line-6-font", function(event) { 
    $('<link>') 
     .appendTo($('head')) 
     .attr({type : 'text/css', rel : 'stylesheet'}) 
     .attr('href', 'fonts/'+$(this).val()+'-font.css'); 
    $(this).prev().css("font-family", $(this).val()); 
}); 
+0

html如何可以使用不同的選擇器來選擇所有的選擇器? – Wilmer

回答

5

是的,你可以這樣做:

$("body").on("click", "[id^='line-'][id$='-font']", function(event) { 
    $('<link>') 
     .appendTo($('head')) 
     .attr({type : 'text/css', rel : 'stylesheet'}) 
     .attr('href', 'fonts/'+$(this).val()+'-font.css'); 
    $(this).prev().css("font-family", $(this).val()); 
}); 

但你可以添加一個普通類給他們,並指它像

$('body').on('click','.yourClass',function(){ 
    ... // your code goes here 
}); 
-1

分配一個類到所有相關的id並將事件綁定到c姑娘。