在下面的代码中,您可以看到我正在一遍又一遍地运行这段代码只需更改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());
});
Run Code Online (Sandbox Code Playgroud)
//
// 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());
});
Run Code Online (Sandbox Code Playgroud)
是的,你可以这样做:
$( "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());
});
Run Code Online (Sandbox Code Playgroud)
但是你可以为它们添加一个公共类并引用它
$('body').on('click','.yourClass',function(){
... // your code goes here
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |