I have a method which take obj as parameter. I can't change the signature and I wan to reuse it. I have to send an element as object to this parameter so not sure how to do it. Can anyone show me?
我有一个方法把obj作为参数。我不能更改签名,我要重新使用它。我必须将一个元素作为对象发送给这个参数,所以不知道该怎么做。谁能告诉我?
function someUsefulFunction(obj) {
var id = obj.id;
//do other stuff
}
{
...
var myElement = $('#myElement');
someUsefulFunction(myElement); //getting error "TypeError: obj.id is undefined"
...
}
2 个解决方案
#1
4
var myElement = document.getElementById('myElement');
looks like its expecting a dom node, so you can do this the old fashioned plain js way.
看起来它希望有一个dom节点,所以您可以使用老式的普通js方式来实现这一点。
or if you want to do it with jquery,
如果你想用jquery,
var myElement = $('#myElement').get(0);
#2
4
You need to change to this:
你需要改变一下:
var id = obj[0].id;
function someUsefulFunction(obj) {
var id = obj.id;
console.log(id);
}
var myElement = $('#myElement').get(0);
someUsefulFunction(myElement);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myElement"></div>
Alternative you can:
选择您可以:
var myElement = $('#myElement').get(0);
function someUsefulFunction(obj) {
var id = obj[0].id;
console.log(id);
}
var myElement = $('#myElement');
someUsefulFunction(myElement);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myElement"></div>
#1
4
var myElement = document.getElementById('myElement');
looks like its expecting a dom node, so you can do this the old fashioned plain js way.
看起来它希望有一个dom节点,所以您可以使用老式的普通js方式来实现这一点。
or if you want to do it with jquery,
如果你想用jquery,
var myElement = $('#myElement').get(0);
#2
4
You need to change to this:
你需要改变一下:
var id = obj[0].id;
function someUsefulFunction(obj) {
var id = obj.id;
console.log(id);
}
var myElement = $('#myElement').get(0);
someUsefulFunction(myElement);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myElement"></div>
Alternative you can:
选择您可以:
var myElement = $('#myElement').get(0);
function someUsefulFunction(obj) {
var id = obj[0].id;
console.log(id);
}
var myElement = $('#myElement');
someUsefulFunction(myElement);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myElement"></div>