1

原始问题

是否有一个 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 毫秒

4

2 回答 2

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');

在这里查看它的实际效果:http: //jsfiddle.net/fkHLc/

于 2012-05-15T00:04:48.023 回答
2

由于.val主要用于元素,您可以使用选择器input编写一些内容::input

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

或者,如果您想更具体,可以使用多重选择器

if (this.is("input, textarea, select" /*, etc. */) {
    this.val(value);
} else {
    this.html(value);
}
于 2012-05-14T23:59:57.123 回答