0

我的代码如下:

const pagedata = {
    name: "Value for name",
    email: "Value for email",
  };

$(".fillvalfromvar").val(pagedata[$(this).attr("id")]);

我需要fillvalfromvar用元素 id 指向的变量的值填充所有具有该类的元素。例如 HTML 如下:

<input id="name" class="fillvalfromvar" type="text">
<input id="email" class="fillvalfromvar" type="text">

我想分别用和填充那些vals 。pagedata["name"]pagedata["email"]

但该this值并未指向原始元素。我应该改用什么?

4

4 回答 4

4

使用接受函数作为参数的语法

$('.fillvalfromvar').val( function(){
   return pagedata[ this.id ];
});

假设这些input元素有fillvalfromvar


或者你可以使用该.each()方法

$('.fillvalfromvar').each( function(){
   this.value = pagedata[ this.id ];
});
于 2013-05-23T09:45:30.120 回答
0

只需使用 $.each

$('.fillvalfromvar').each(function(){
   $(this).val(pagedata[$(this).attr('id')]);
});

或者$('input[id]')如果这些输入没有提到的类,则使用

于 2013-05-23T09:49:30.000 回答
0

尝试这个

$('.fillvalfromvar').each(function(){
     $(this).val(pagedata[$(this).attr('id')]);
})
于 2013-05-23T09:50:24.713 回答
-1

您需要定义输入文本的类:

<input id='name' type='text'  class="fillvalfromvar">
<input id='email' type='text' class="fillvalfromvar">

请试试这个。

于 2013-05-23T09:45:29.173 回答