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

时间:2016-04-04 11:50:37

标签: javascript jquery

我是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());
  }
);

5 个答案:

答案 0 :(得分:2)

正如jQuery文档中所述......

  

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

改为使用.val()。

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

<强> Working Demo

答案 1 :(得分:1)

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

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

DEMO

答案 2 :(得分:1)

输入有.val()来读取值

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

答案 3 :(得分:1)

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

您必须更改以下使用的脚本。

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

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

答案 4 :(得分:1)

   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());
   });