如何在jquery中通过自定义属性获取输入字段的值

How to get the value of input field by custom attribute in jquery

本文关键字:输入 获取 字段 自定义属性 jquery      更新时间:2023-12-20

我完全是jquery的初学者。

我试过这个https://jsfiddle.net/0xLqhufd/2/

<body>
<div>
<input type="text" person="firstName" value="John">
<input type="text" person="birthDate" value="September 1st, 2000">
</div>
</body>

但我在警报中一片空白:

$('input[person]').each(function(index) {
    alert(index + ': ' + $(this).text());
  }
);

正如jQuery文档中所说。。。

.text()方法不能用于表单输入或脚本

请改用.val()。

$('input[person]').each(function(index) {
    alert(index + ': ' + $(this).val());
  }
);

工作演示

在void元素中,使用text()是不合适的。请改用.val()input[type=text]是一个void元素,这意味着它内部不能有任何子节点,包括text nodes

$('input[person]').each(function(index) {
    alert(index + ': ' + $(this).val());
});

演示

input具有.val()来读取值

$('input[person]').each(function(index) {
    alert(index + ': ' + $(this).val());//will read input value
  }
);

我对你的怀疑有一个答案。

您必须更改已使用的脚本,如下所示。

$('input[person]').each(function(index) {
    alert(index + ': ' + $(this).val());
  }
);

如果你发现我的代码对你有用,请更新我。

   Hey you can use like this:-
   input "type=text" tags have the values not text.
   that's why you have to use .val() instead of .text().
   $('input[person]').each(function(index) {
       alert(index + ': ' + $(this).val());
   });