javascript jquery 获取跨度值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24372194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:39:43  来源:igfitidea点击:

jquery get span value

javascriptjquery

提问by Blynn

I'm struggling to get the value of a span tag and then pass the value into the input field on click.

我正在努力获取 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>  

回答by Rajaprabhu Aravindasamy

You have totally two mistakes in your code,

你的代码有两个错误,

  1. remove the quotes surrounded by the thisreference

    var key = $(this).text();

  2. input[type=text] is a void element, you are trying to append text into it, so it is invalid.

    $("input").val(key); //use .val() instead of .append()

  1. 去除由包围引号this的参考

    var key = $(this).text();

  2. input[type=text] 是一个空元素,您试图将文本附加到其中,因此它无效。

    $("input").val(key); //use .val() instead of .append()

Full code would be,

完整的代码是,

$(".kb .row span").on("click", function() {
  $("input").val($(this).text());
});

For appending the values just use like,

要附加值,只需使用类似,

$(".kb .row span").on("click", function() {
  var text = $(this).text();
  var elem = $('input');
  elem.val(elem.val() + text);
});

DEMO

演示

回答by tymeJV

thisdoes not need quotes (else you're literally looking for an element like <this>):

this不需要引号(否则您实际上是在寻找像 一样的元素<this>):

var key = $(this).text();

回答by Christopher Marshall

http://jsfiddle.net/dgmT5/

http://jsfiddle.net/dgmT5/

Your $(this)reference was wrong and you should use .val()to change inputs value.

您的$(this)参考是错误的,您应该使用.val()来更改输入值。

$(".kb .row span").on("click", function() {
  var key = $(this).text();
  alert(key)
  $("body").find("input").val(key);
});