最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - using this in javascript function - Stack Overflow

programmeradmin0浏览0评论

I have code like this

<img onclick="getTitle();" title="myimg" >  
function getTitle()  
{  
alert(jQuery(this).attr("title");  
}  

and its not working. Can somebody explain how to do this right. And what is wrong with this code.

I have code like this

<img onclick="getTitle();" title="myimg" >  
function getTitle()  
{  
alert(jQuery(this).attr("title");  
}  

and its not working. Can somebody explain how to do this right. And what is wrong with this code.

Share Improve this question asked Jun 27, 2011 at 16:54 Tony_MTony_M 692 silver badges8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

As @Neal says, if you use jQuery, use it properly.


Nevertheless here is an explanation why your code does not work:

this refers to window inside the function. You can set this explicitly by using .call():

<img onclick="getTitle.call(this);" title="myimg" >
<!-- `this` only refers to the element inside the handler --> 

or you have to pass the element explicitly as argument:

<img onclick="getTitle(this);" title="myimg" >

Then you have to change your function too:

function getTitle(element)  {  
    alert(element.getAttribute('title'));
}  

For more information about this type of event handling model, read this article on quirksmode about early event handlers.

There is another one which explains this in the context of event handlers.

The best is if you read all the articles about event handling and learn about the different models. You actually should not bind event handlers through HTML attributes anymore.

For the sake of pleteness, without jQuery, a better why is to attach the event handler to the DOM property. Assuming your image has an ID

<img id="myimg" title="myimg" />

the necessary JavaScript would be:

function getTitle()  {  
    alert(this.getAttribute('title'));
}  
document.getElementById('myimg').onclick = getTitle;

This code has to e after the element in the HTML.

you left off a )

function getTitle()  
{  
    alert(jQuery(this).attr("title"));  
}  

Also since you are using jQuery it might be better to do this:

<img id="imgID" title="myimg" >  

jQuery('#imgID').click(function(){  
   alert(this.title);  
})

You forgot the <script></script> tags and you are also missing a ) at the end of the alert() function. You also need to pass this in the onclick function so that you know which item is being called.

<script>
function getTitle(element)  {
    var objTitle = jQuery(element).attr("title"); 
    alert(objTitle); 
}
</script>
<img onclick="getTitle(this);" title="myimg" />

Also, having the <script> before will ensure this particular function works.

Or, to make it even more simpler, you could do this:

<script>
function getTitle(elementTitle)  { 
    alert(elementTitle); 
}
</script>
<img onclick="getTitle(this.title);" title="myimg" />
发布评论

评论列表(0)

  1. 暂无评论