原始问题
是否有一个 jQuery 方法可以检查选择类型并适当地设置值?例如,使用 .html() 或 .val()。
我已经制定了自己的方法来为我完成这项工作,但是我不确定这是否是执行这项任务的最佳方式。
$.fn.data = function(value) {
if(this.is("input")){
this.val(value);
}else if(... other type ...){
this.val(value);
}else{
this.html(value);
}
};
我也看过使用 tagName 属性。var type = this.prop("tagName").toLowerCase();
编辑:
基准测试
对于任何感兴趣的人,我在 this.tagName; 之间做了一些基准测试。和 $(this).is("input"); 有 10,000 条记录。
this.tagName.toLowerCase();
x 10,000 条记录 = 185 毫秒
$(this).is("input");
x 10,000 条记录 = 1676 毫秒