jQuery :如何访问元素的名称

jQuery : how to access the name of the element

本文关键字:元素 访问 何访问 jQuery      更新时间:2023-09-26

请看下面的html代码

<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>

和 jquery 代码

$( "input[id*='product']" ).val( 'test' );
结果将显示 4 个文本框,默认值为"test",

但现在我喜欢显示 4 个带有产品名称值的文本框,这意味着第一个文本框将显示"三星",第二个文本框将显示"Apple"等,那么我应该在 jQuery 代码中输入什么命令? 请指教。

只需使用 .val(fn)

$("input[id^='product_']").val(function() {
        return this.name;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>

对于每个输入元素,它将调用将返回要设置的值的函数。

奖金

为了使它更加简洁,您可以考虑一个辅助函数,例如:

jQuery.prop = function(name) {
    return function() {
        return this[name];
    }
};

然后,代码变为:

$("input[id^='product_']").val($.prop('name'));

试试这个:

$("input[id*='product']").each(function() {
  $this = $(this);
  $this.val($this.attr("name"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>

$("input[id*='product']").each(function () {
    var $this = $(this);
    $this.val($this.prop("name"));
});

JSFiddle