简体   繁体   中英

jquery get span value

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

$( 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>  

You have totally two mistakes in your code,

  1. remove the quotes surrounded by the this reference

    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()

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

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

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

http://jsfiddle.net/dgmT5/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM