如何将 jQuery 点击事件应用于多个 ID
How to apply a jQuery click event to multiple ID's
在下面的代码中,您可以看到我正在一遍又一遍地运行此代码块,只是更改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());
});
是的,你可以这样做:
$( "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
});
将一个类分配给所有相关的 id,并将事件绑定到该类。
相关文章:
- 将函数的上下文应用于javascript变量
- 将CSS应用于printWindow.print();在Javascript中
- 如何将CSS(特别是填充/边距)应用于select下拉菜单的选项或optgroup
- javascript点击函数不;不适用于ID和Class
- 如何编写用于id验证的正则表达式(JavaScript)
- $scope.apply()何时应用于angular
- Javascript非常简单:'阅读更多''显示较少'应用于Wordpress的功能
- 尝试应用于<tr>在ng单击中
- 如何将javascript仅应用于1个表单中的2个表单提交按钮中的1个
- 将脚本应用于Angular 2上的输入
- Json和$scope的角度之间的差异$eval应用于JSON字符串时
- 如何将参数应用于String.prototype.format函数
- 动态地将过滤器应用于 JSON.parse()
- $location更改不适用于ngchange,而是应用于ngclick
- 如何将 :empty 选择器应用于 XML 文档
- 如何仅在文本字段中有值时才将自定义过滤器应用于 ng-repeat
- 如何使用 JavaScript 将样式应用于 CKEditor 中的选定文本
- MongoDB 无法将$addToSet应用于 Meteor JS 中的非数组
- addClass() 函数未应用于 ID
- 如何获取浏览器视口宽度&高度在Javascript和应用于CSS ID's