JQuery get content of span

后端 未结 6 1702
萌比男神i
萌比男神i 2021-02-19 00:29

I\'m trying to get the content of a span when a button is clicked. This is the html:

相关标签:
6条回答
  • 2021-02-19 00:50

    The span isn't a parent of the '.select-location' button, but the div is (which the span is in). Using your markup, try something like this:

    var spanVal = $(this).parent('.multiple-result').find('span').html();
    
    0 讨论(0)
  • 2021-02-19 00:54
    $('button.select-location').live('click', function(event){
    
      var span_val = $(this).next("span").html();
    
      alert('selecting...' + span_val);
    
    });
    
    0 讨论(0)
  • 2021-02-19 00:54

    Here is a Jsfiddler demo using jQuery next

    http://jsfiddle.net/vVK54/1/

    $('button.select-location').live('click', function(event){      
      // set the span value
      var span_val = $(this).next().html();
      alert('selecting...' + span_val);
    });
    
    0 讨论(0)
  • 2021-02-19 00:58

    You want to get the parent first, then find the span:

    var span_val = $(this).parent().find("> span").html(); 
    

    Edit: Ever go back and look at code you wrote 2 years ago and groan, "Why did I do that?". The above code is awkward. Instead of .find("> span"), I should have used .children("span").

    var span_val = $(this).parent().children("span").html(); 
    

    But, what is a child of your parent? A sibling! So, instead of .parent().children("span"), I should have used .siblings("span").

    var span_val = $(this).siblings("span").html();
    

    But, looking at the HTML, we don't even need to dig through the siblings, we know it's the next sibling:

    var span_val = $(this).next("span").html();
    

    or just:

    var span_val = $(this).next().html();
    

    By this point, we're barely using jQuery at all. We could just say:

    var span_val = this.nextSibling.innerHTML;
    

    But, maybe now I've swung the pendulum too far the other way?

    0 讨论(0)
  • 2021-02-19 00:59

    Depending on how many spans you have but if the span will always come directly after the button then the .next('span') will work. If you plan on placing the button anywhere else within the same parent div then you will need to navigate the dom to find it.

    $('selector').click(function() {
        $(this).parent().find('span');
    )};
    

    Also it may be best to add a targetable class or attribute to the span to target it better incase you do plan on a more complex dom or multiple spans.

    <span class='clicktarget'>Text Here</span>
    
    $('button.select-location').click(function() {
        var span_val = $(this).parent('div').find('span.clicktarget').html();
    });
    

    Hope this helps

    0 讨论(0)
  • 2021-02-19 01:09

    It's not button's parent. div is button's parent and span is children of the div. Try

    var span_val = $(this).parent().children("span").html();
    

    instead.

    Working demo

    0 讨论(0)
提交回复
热议问题