我很难获得span标记的值,然后在点击时将值传递到输入字段。
$( document ).ready(function() {
$( "input" ).on( "click", function() {
$( ".kb" ).toggle();
});
$( ".kb .row span" ).on( "click", function() {
var key = $('this').text();
alert(key)
$("body").find("input").append(key);
});
});
<input type="text" />
<div class="kb">
<div class="row">
<span>q</span>
<span>w</span>
<span>e</span>
<span>r</span>
<span>t</span>
<span>y</span>
<span>u</span>
<span>i</span>
<span>o</span>
<span>p</span>
<span>[</span>
<span>]</span>
</div>
<div class="row">
<span>a</span>
<span>s</span>
<span>d</span>
<span>f</span>
<span>g</span>
<span>h</span>
<span>j</span>
<span>k</span>
<span>l</span>
<span>;</span>
<span>'</span>
</div>
<div class="row">
<span>z</span>
<span>x</span>
<span>c</span>
<span>v</span>
<span>b</span>
<span>n</span>
<span>m</span>
<span>,</span>
<span>.</span>
<span>/</span>
</div>
答案 0 :(得分:3)
你的代码中有两个错误,
删除this
引用
var key = $(this).text();
input [type = text]是一个void元素,您试图将文本附加到其中,因此它无效。
$("input").val(key); //use .val() instead of .append()
完整代码将是,
$(".kb .row span").on("click", function() {
$("input").val($(this).text());
});
要附加值,请使用like,
$(".kb .row span").on("click", function() {
var text = $(this).text();
var elem = $('input');
elem.val(elem.val() + text);
});
答案 1 :(得分:1)
this
不需要引号(否则你真的在寻找像<this>
这样的元素):
var key = $(this).text();
答案 2 :(得分:1)
您的$(this)
引用错误,您应该使用.val()来更改输入值。
$(".kb .row span").on("click", function() {
var key = $(this).text();
alert(key)
$("body").find("input").val(key);
});