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

javascript - this.text Function - Stack Overflow

programmeradmin2浏览0评论

I have a inline function that works fine. When the link is clicked it puts the text into the textField:

 <a href="#" onclick="document.getElementById('textField').value =(this.text);">someText</a>

What i want to do is be able to call the above as a function instead of writing it inline. Example:

function setValue() {
      document.getElementById('dd').value =(this.text);
}

and be able to call it like so:

<a href="#" onclick="setValue();">someText</a>

I thought it would be simple but for some reason it is not work and giving me error in firebug. I think it has something to do with "this.text" being called from a function instead of inline. Thanks for any help.

I have a inline function that works fine. When the link is clicked it puts the text into the textField:

 <a href="#" onclick="document.getElementById('textField').value =(this.text);">someText</a>

What i want to do is be able to call the above as a function instead of writing it inline. Example:

function setValue() {
      document.getElementById('dd').value =(this.text);
}

and be able to call it like so:

<a href="#" onclick="setValue();">someText</a>

I thought it would be simple but for some reason it is not work and giving me error in firebug. I think it has something to do with "this.text" being called from a function instead of inline. Thanks for any help.

Share Improve this question asked Dec 27, 2011 at 0:01 user982853user982853 2,45015 gold badges59 silver badges85 bronze badges 1
  • Well, what does the error say? You seem to not know this but errors actually provide useful information about themselves (a message and the line number). – Šime Vidas Commented Dec 27, 2011 at 0:49
Add a ment  | 

4 Answers 4

Reset to default 2

Why not take it one step further and put the event binding code outside of the markup too? Separating your behavior from presentation is a good idea.

$("#anchor_selector").click(function () {
    $("#dd").val(this.text);
});

I would apply an id attribute to your anchor and use it in the selector. Or you can use one of the many other selectors out there to target your link.

function setValue( text ) {
   jQuery('#dd').val( text );
}
<a href="#" onclick="setValue( jQuery( this ).text() );">someText</a>

You need to pass the context, otherwise this will be the global scope (window):

<a href="#" onclick="setValue(this);">someText</a>

function setValue(context) {
      document.getElementById('dd').value = $(context).text();
}

The this is being lost. Try setting setValue() to take a reference to the element as the first param, and then pass this in the handler.

发布评论

评论列表(0)

  1. 暂无评论