在将其设置为空字符串之前,如何存储元素属性供以后使用?
我有以下JQuery代码:
$(targetSelector) .attr('data-disabled', 'yes') .attr('title', '') .addClass('disabled') .prop('disabled', true);
如何更改此代码,以便在title属性设置为”之前,我将获取标题的当前值并将其存储在’data-title’属性中。
你可以这样做:
$(targetSelector).attr({ 'data-disabled': 'yes', 'data-title': function() { return this.title } 'title': '' }).addClass('disabled').prop('disabled', true);
其他答案是相似的,但访问this.title
只有在this
是元素时才会起作用,这取决于上下文。 上面的方法使用function属性来返回标题。
我建议:
$(targetSelector).attr({ 'data-disabled': 'yes', 'data-title': function() { return this.title; } }).attr('title', '').addClass('disabled').prop('disabled', true);
JS小提琴演示 。
参考文献:
-
attr()
。 -
data()
。
试试这个
$(targetSelector) .attr({'data-disabled' : 'yes', 'data-title' : function() {return this.title;}}) // set the title before it is removed .attr('title', '') .addClass('disabled') .prop('disabled', true);
试试这个
$(targetSelector) .attr('data-disabled' : 'yes') .attr('data-title', $(this).attr('title')) .attr('title', '') .addClass('disabled') .prop('disabled', true);