jQuery设置值取决于tagName

时间:2012-05-14 23:57:32

标签: jquery

原始问题

是否有一个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(“输入”);有10,000条记录。

this.tagName.toLowerCase(); x 10,000条记录= 185毫秒

$(this).is("input"); x 10,000条记录= 1676毫秒

2 个答案:

答案 0 :(得分:3)

您可以使用插件格式:

$.fn.setVal = function(value) {

    return this.each(function() {

        if ($.inArray( this.tagName.toLowerCase(), ['input', 'textarea', 'select'] ) != -1) {
            $(this).val( value );
        } else {
            $(this).text( value );
        }       
    });
};

按如下方式使用:

$('input, span').setVal('Some Value');

在此处查看:[{3}}

答案 1 :(得分:2)

由于.val主要用于input元素,因此您可以使用:input selector编写内容:

if (this.is(":input")) {
   this.val(value);
} else { 
   this.html(value);
}

或者如果您想更具体一点,可以使用multiple selector

if (this.is("input, textarea, select" /*, etc. */) {
    this.val(value);
} else {
    this.html(value);
}
相关问题