jQuery : 버튼을 클릭 할 때 가장 가까운 값을 얻는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/1877545

  •  18-09-2019
  •  | 
  •  

문제

이 코드가 작동하지 않는 것 같습니다. 버튼을 클릭하면 가장 가까운 값을 얻으려면 어떻게해야합니까?

가장 가까운 정의

IE : "A :"인 경우 버튼을 클릭하면 10의 값을 원합니다. "B :"에 나열된 버튼을 클릭하면 20의 값을 원합니다.

코드는 다음과 같습니다.

<script type="text/javascript">
$(function(){

 $('.test').click(function(){
  var value = $(this)
     .parent()
     .parent()
     .closest(".abc")
     .attr("value")
  alert(value);
  return false
 });

});
</script>
<form name="myform">
<table>
 <tr>
     <td>A:</td>
        <td><input type="text" class="abc" name="a" id="a" value="10" /></td>
        <td><input type="text" name="vbn" id="vbn" /></td>
        <td><input type="text" name="mkl" id="mkl" /></td>
        <td><input type="button" class="test" name="test" id="test" value="test" /></td>
        <td>B:</td>
        <td><input type="text" class="abc" name="b" id="b" value="20" /></td>
        <td><input type="text" name="ews" id="ews" /></td>
        <td><input type="text" name="hrs" id="hrs" /></td>
        <td><input type="text" name="ew3" id="ew3" /></td>
        <td><input type="text" name="3ws" id="3ws" /></td>
        <td><input type="button" class="test" name="test" id="test" value="test" /></td>
    </tr>
    <tr>
     <td>C:</td>
        <td><input type="text" class="abc" name="c" id="c" value="30" /></td>
        <td><input type="text" name="oiu" id="oiu" /></td>
        <td><input type="text" name="dfe" id="dfe" /></td>
        <td><input type="button" class="test" name="test" id="test" value="test" /></td>
    </tr>
    <tr>
     <td>D:</td>
        <td><input type="text" class="abc" name="d" id="d" value="40" /></td>
        <td><input type="button" class="test" name="test" id="test" value="test" /></td>
    </tr>
</table>
</form>
도움이 되었습니까?

해결책

얼마 전, 나는이 상황에서 도움이 될 수있는 플러그인을 썼습니다.

당신은 이것을 사용합니다 :

$(":button").click(function() {
    $(this).prevALL("td:has(.abc)").eq(0).find(".abc").val();
});

다른 팁

$('input.test').click(function() {

    $(this).parent()
           .prevAll('td:has(input.abc)')
           .find('input.abc:last')
           .val();

});

여기에 있습니다 작동하는 데모

HTML 코드가 동일한 ID를 갖는 여러 요소와 부적절하게 형식화되어 있다는 사실을 무시하면이 JavaScript 코드가 생각하는 것을 수행하지 않습니다. 참조 http://docs.jquery.com/traversing/closest, closest() 당신이있는 곳에서 나무를 바라본다. 요소 일치가 없습니다 .abc 버튼 바로 위의 나무에서. 당신이 찾고있는 것은 부모가 아니라 이웃입니다.

나는 다음과 같은 것을 시도 할 것입니다.

$(".test").click(function() {
  $(this).parent().parent().find(".abc").val();
});

그러나 특정 버튼 근처에서 여러.ABC가 문제를 해결하지 못합니다.

코드를 "올바르게"작성하고 버튼이 ID와 여러 클래스를 사용하여 필드를 직접 참조하는 것이 어떻습니까?

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