简体   繁体   English

使用$(this).attr('src'); 在img上未定义

[英]function with $(this).attr('src'); undefined on img

I need help on understand how the $(this) work exactly because i can't bring this simple code to work: 我需要帮助来了解$(this)的工作原理,因为我无法将以下简单代码发挥作用:

HTML: HTML:

<img style="cursor:pointer;" onclick="openfullsize();" src="/customimage/test.png"/>

JS: JS:

function openfullsize(){
    var path = $(this).attr("src");
    alert(path);
}

I wonder if there is anything i'm doing wrong or if I just don't understand how $(this) behave. 我想知道我是否做错了什么,或者我只是不了解$(this)的行为。 $(this) should refer to the element from which it is invoked, right? $(this)应该引用调用它的元素,对吗? in this case, it would be my img. 在这种情况下,这将是我的img。

This should alert the content of the src attribute but it is undefined. 这应该提醒src属性的内容,但未定义。

I would like this to be in Jquery please. 我希望这可以在Jquery中使用。

Thanks for your help and here is the JsFiddle 感谢您的帮助,这里是JsFiddle

You should bind the event-handler directly in the JS code instead of in the HTML like you're doing at the moment. 您应该将事件处理程序直接绑定到JS代码中,而不是像现在那样绑定到HTML中。

$("img").on("click", function(){
    //$(this) will now work as expected
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM