[英]Jquery undefined error for getting attribute of an element
I have the following code: 我有以下代码:
<a id="1" href"javascript:void(0)" onclick="myfunc();" class="a">click</a>
myfunc(){
var $id=$(this).attr('id');
console.log($id);
}
I am getting undefined error ... and can't figure it out. 我收到未定义的错误...并且无法弄清楚。 can any one tell me what is happing?
有人可以告诉我什么吗?
*.js * .js
$(document).on("click",".a",function(){
console.log($(this).attr("id"));
});
Using jquery you can handle when the element is clicked and get any attribute with $(this).attr("attribute")
使用jquery可以处理单击元素的时间,并可以通过
$(this).attr("attribute")
获得任何属性
*.html * .html
<a id="1" href"javascript:void(0)" class="a">click</a>
I'm going to assume the following code which fixes your syntax. 我将假设以下代码可修复您的语法。 Please let me know if I am wrong assuming this:
假设这样做有误,请告诉我:
<a id="1" href="javascript:void(0)" onclick="myfunc()" class="a">click</a>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function myfunc(){
var $id=$(this).attr('id');
console.log($id);
}
</script>
Your function is actually simply calling myfunc in the global context and the this
keyword is referencing window
rather than the <a>
element. 您的函数实际上只是在全局上下文中调用myfunc,而
this
关键字引用的是window
而不是<a>
元素。 To fix this, either use onclick="myfunc.call(this)"
. 要解决此问题,请使用
onclick="myfunc.call(this)"
。 The complete code is: 完整的代码是:
<a id="1" href="javascript:void(0)" onclick="myfunc.call(this)" class="a">click</a>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function myfunc(){
var $id=$(this).attr('id');
console.log($id);
}
</script>
<a id="1" href="javascript:void(0)" onclick="myfunc()" class="a">click</a>
myfunc(){
var $id=$(this).attr('id');
console.log($id);
}
you were missing a ton of ""
and =
and stuff 您缺少大量的
""
和=
东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.