无法将输入元素传递到函数中以获取数据属性

时间:2018-08-18 14:38:39

标签: javascript jquery

能否请您看一下这个演示,让我知道为什么我无法将$("#sample")传递给以下函数?

function GetAtts(elem) {
  var x = elem.data('x');
  var y = elem.data('y');

 console.log(x + ' ' + y); 
}


function GetAttsThis(elem) {
  var x = this.data('x');
  var y = this.data('y');

 console.log(x + ' ' + y); 
}

GetAtts('sample');
GetAtts('$("#sample")');
GetAttsThis('sample');

这是演示

function GetAtts(elem) {
  var x = elem.data('x');
  var y = elem.data('y');

  console.log(x + ' ' + y);
}


function GetAttsThis(elem) {
  var x = this.data('x');
  var y = this.data('y');

  console.log(x + ' ' + y);
}

GetAtts('sample');
GetAtts('$("#sample")');
GetAttsThis('sample');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="sample" type="text" data-x="5" data-y="20">

如您所见,我正在

  

未捕获的TypeError:elem.data不是函数

  

未捕获的TypeError:this.data不是函数

两种功能的格式

2 个答案:

答案 0 :(得分:1)

您必须像这样传递对象:

GetAtts($("#sample"));

this关键字不引用输入,因为您在没有特定上下文的情况下使用它。

您可以改用.apply()方法在函数范围内将this设置为$("#sample"),例如:

GetAttsThis.apply($("#sample"));

function GetAtts(elem) {
  var x = elem.data('limitn');
  var y = elem.data('limitp');

  console.log(x + ' ' + y);
}

function GetAttsThis() {
  var x = this.data('limitn');
  var y = this.data('limitp');

  console.log(x + ' ' + y);
}

GetAtts($("#sample"));
GetAttsThis.apply($("#sample"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="sample" type="text" data-limitn="5" data-limitp="20">

答案 1 :(得分:1)

您实际上几乎拥有了它。在GetAtts('$("#sample")');上,您需要删除单引号。这将使$("#sample")选择实际的元素,并将其传递给GetAtts函数。

function GetAtts(elem) {
    var x = elem.data('x'); // Your attribute data has property x and y. It doesnt have limitn, and limitp
    var y = elem.data('y'); 
    console.log(x + ' ' + y); 
}

function GetAttsThis(elem) {
    var val = eval(elem);
    var x = val.data('x');
    var y = val.data('y'); 
}

// You need to pass in the actual jQuery element
GetAtts($("#sample"));
GetAttsThis('$("#sample")');
// GetAtts('sample'); // This will not work. THis will pass a string
// GetAtts('$("#sample")'); // This will not work. THis will pass a string that represent working code. All you have to do here is remove surrounding single quotations
// GetAttsThis('sample'); // This will not work. THis will pass a string
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="sample" type="text"  data-x="5" data-y="20">

仅供参考:

如果您真的想向参数发送字符串,我将您的代码固定在GetAttsThis函数上。我使用eval()来评估输入字符串。那不是很好的编码方式,但是只是觉得您可能会喜欢...:)