如何获取读取元素上的数据属性的特定变量?

时间:2018-03-03 19:04:11

标签: javascript jquery html

我的网站上有一些字段,它们是相同的,但是每一个都应该用它的值更新一些jquery变量。

<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>

我需要根据数据属性,它们运行相同的函数,但更新属性中指向的变量。

示例:

for = "0";
int = "0";
agi = "0";

$( "input" ).focusout(function() {
    data-atribute-of-the-element = $(this).val;
})

我不知道该怎么做。 为每个输入创建不同的功能似乎很愚蠢。

提前致谢!

4 个答案:

答案 0 :(得分:1)

创建一个具有变量字段的对象。像下面的东西。

var a={'for':'0','int':'0','agi':'0'}

$( "input" ).focusout(function() {
    a[$(this).attr('data-atribute')] = $(this).val();
    console.log(a.for);
    console.log(a.int);
    console.log(a.agi);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>

答案 1 :(得分:1)

.attr()确实有效,但由于您仍在使用数据属性,因此您也可以使用为其设计的.data()函数。

请参阅代码段中的注释以获取解释:

&#13;
&#13;
/* Set up an object to contain the values you're capturing.
   This means we won't have to predefine all the variables or 
   set them individually; it also means you can use reserved words 
   like "for", which wouldn't work as variables on their own: */
var capturedValues = {};

$( "input" ).focusout(function() {

  // This gets the contents of the "data-atribute" attribute:
  var theName = $(this).data("atribute");

  // This captures the value of the current input field,
  // and puts it in the capturedValues object using theName as the key:
  capturedValues[theName] = $(this).val();
  // Later on you can reference these as e.g. capturedValues.agi
  
  // Show the results (just for demo):
  console.log(capturedValues);

})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用jQuery的.attr函数:

$( "input" ).focusout(function() {
    let data-atribute-of-the-element = $(this).attr('data-atribute');
})

答案 3 :(得分:0)

怎么样:

this.state

PS:&#39;属性&#39;有2 t&#39; s:属性