Programing

Jquery를 사용하여 부모 div의 ID 찾기

crosscheck 2020. 8. 20. 07:37
반응형

Jquery를 사용하여 부모 div의 ID 찾기


다음과 같은 HTML이 있습니다.

<div id="1">
    <p>
        Volume = <input type="text" />
        <button rel="3.93e-6" class="1" type="button">Check answer</button>
    </p>
    <div></div>
</div>

다음과 같은 일부 JS :

$("button").click(function () {
    var buttonNo = $(this).attr('class');
    var correct = Number($(this).attr('rel'));

    validate (Number($("#"+buttonNo+" input").val()),correct);
    $("#"+buttonNo+" div").html(feedback);
});

내가 정말로 원하는 것은 버튼에 class = "1"이 필요하지 않은 경우입니다 (숫자 클래스가 유효하지 않다는 것을 알고 있지만 이것은 WIP입니다!). 상위 div의 ID입니다. 실제 생활에는 이와 같은 여러 섹션이 있습니다.

  1. 버튼을 부모로 지정하는 div의 ID를 어떻게 찾습니까?

  2. 버튼 코드에 답변을 저장하는 더 의미있는 방법은 무엇입니까? 프로그래머가 아닌 사람이 내용을 깨지 않고 복사하여 붙여 넣을 수 있도록 가능한 한 완벽하게 만들고 싶습니다!


상위 div에서 이벤트 위임사용할 수 있습니다 . 또는 가장 가까운 방법을 사용하여 버튼의 부모를 찾습니다.

둘 중 가장 쉬운 것이 아마도 가장 가까운 것입니다.

var id = $("button").closest("div").prop("id");

1.

$(this).parent().attr("id");

2.

많은 방법이있을 것입니다! 하나는 답을 포함하는 요소를 숨기는 것일 수 있습니다.

<div>
    Volume = <input type="text" />
    <button type="button">Check answer</button>
    <span style="display: hidden">3.93e-6&lt;/span>
    <div></div>
</div>

그런 다음 위와 유사한 jQuery 코드를 사용하여이를 잡으십시오.

$("button").click(function () 
{
    var correct = Number($(this).parent().children("span").text());
    validate ($(this).siblings("input").val(),correct);
    $(this).siblings("div").html(feedback);
});

클라이언트 코드에 답을 넣으면 볼 수 있다는 점을 명심하십시오. 이렇게하는 가장 좋은 방법은 서버 측에서 유효성을 검사하는 것이지만 범위가 제한된 앱의 경우 문제가되지 않을 수 있습니다.


이 시도:

$("button").click(function () {
    $(this).parents("div:first").html(...);
});

$(this).parents('div').attr('id');

상위 div의 ID를 얻으려면 :

$(buttonSelector).parents('div:eq(0)').attr('id');

또한 코드를 상당히 리팩토링 할 수 있습니다.

$('button').click( function() {
 var correct = Number($(this).attr('rel'));
 validate(Number($(this).siblings('input').val()), correct);
 $(this).parents('div:eq(0)').html(feedback);
});

이제 버튼 클래스가 필요하지 않습니다.

explanation
eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
$(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
Thus: $(selector).parents('div:eq(0)'); will match the the first parent div of the elements matched by selector.

You should have a look at the jQuery docs, particularly selectors and traversing:


http://jsfiddle.net/qVGwh/6/ Check this

   $("#MadonwebTest").click(function () {
    var id = $("#MadonwebTest").closest("div").attr("id");
    alert(id);
    });

This can be easily done by doing:

$(this).closest('table').attr('id');

You attach this to any object inside a table and it will return you the id of that table.


JQUery has a .parents() method for moving up the DOM tree you can start there.

If you're interested in doing this a more semantic way I don't think using the REL attribute on a button is the best way to semantically define "this is the answer" in your code. I'd recommend something along these lines:

<p id="question1">
    <label for="input1">Volume =</label> 
    <input type="text" name="userInput1" id="userInput1" />
    <button type="button">Check answer</button>
    <input type="hidden" id="answer1" name="answer1" value="3.93e-6" />
</p>

and

$("button").click(function () {
    var correctAnswer = $(this).parent().siblings("input[type=hidden]").val();
    var userAnswer = $(this).parent().siblings("input[type=text]").val();
    validate(userAnswer, correctAnswer);
    $("#messages").html(feedback);
});

Not quite sure how your validate and feedback are working, but you get the idea.


find() and closest() seems slightly slower than:

$(this).parent().attr("id");

참고URL : https://stackoverflow.com/questions/545978/finding-the-id-of-a-parent-div-using-jquery

반응형