문제

I have the following code:

<div>    
  <span id='1' onclick="GetValue();">Some value</span>
  <span id='2'>Some Span
     <span id='3'>Want this text</span>
  </span>
</div>

 <div>    
  <span id='1' onclick="GetValue();">Some value</span>
  <span id='2'>Some Span
     <span id='3'>Want this text</span>
  </span>
</div>

I need to get the text from span id=3 and this is what I have:

  function GetValue() {
     var get_text= $(this).next().find("#3").text();
     alert(get_text);
  }
도움이 되었습니까?

해결책

Firstly you can directly get the text using id selector like this

$('#myId').text();

Second id attribute's value should not be start with digit. It must be start with character and then it may followed by digit.

The issue with your code is that your $(this) is basically a window object not the span which trigger the click.

So you need to something like this

function GetValue(element) {
     var get_text= $(element).next().find("#three").text();
     alert(get_text);
}

with HTML

<span id='one' onclick="GetValue(this);">Some value</span>
  <span id='two'>Some Span
     <span id='three'>Want this text</span>
  </span>

Js Fiddle Demo

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top