admin管理员组文章数量:1386692
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
4 Answers
Reset to default 2Why 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.
本文标签: javascriptthistext FunctionStack Overflow
版权声明:本文标题:javascript - this.text Function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744494551a2608938.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论