如何使用jQuery锚点设置文本框的值? [英] How do I set a textbox's value using an anchor with jQuery?
问题描述
我有一个文本框,我想根据锚标签的内部文本设置其值.换句话说,当有人点击该锚点时:
I have a textbox whose value I want to set based on the inner text of an anchor tag. In other words, when someone clicks on this anchor:
<a href="javascript:void();" class="clickable">Blah</a>
我希望我的文本框填充文本"Blah".这是我当前正在使用的代码:
I want my textbox to populate with the text "Blah". Here is the code I am currently using:
<script type="text/javascript">
$(document).ready(function(){
$("a.clickable").click(function(event){
$("input#textbox").val($(this).html());
});
});
</script>
在我的html中,有一个锚标签列表,其中包含"clickable"类和一个ID为"textbox"的文本框.
And in my html there is a list of anchor tags with the class "clickable" and one textbox with the id "textbox".
我已经用代码替换了上面的代码,以仅显示带有$(this).html()的javascript警报,并且它似乎显示了正确的值.我也将$(this).html()更改为硬编码字符串,并正确设置了文本框值.但是,当我将它们组合在一起时,文本框就被清除了.我在做什么错了?
I've substituted the code above with code to just show a javascript alert with $(this).html() and it seems to show the correct value. I have also changed the $(this).html() to be a hardcoded string and it setes the textbox value correctly. But when I combine them the textbox simply clears out. What am I doing wrong?
推荐答案
我编写了此代码段,效果很好:
I wrote this code snippet and it works fine:
<a href="#" class="clickable">Blah</a>
<input id="textbox">
<script type="text/javascript">
$(document).ready(function(){
$("a.clickable").click(function(event){
event.preventDefault();
$("input#textbox").val($(this).html());
});
});
</script>
也许您忘记为链接指定一个可点击"的类名了?
Maybe you forgot to give a class name "clickable" to your links?
这篇关于如何使用jQuery锚点设置文本框的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!