简体   繁体   中英

How to reach this element?

<div class="ptp-item-container">
    <div class="plan">Text I want!</div>
    <div class="price">200</div>
    <div class="bullet-item">some other text</div>
    <div class="cta"> <a class="button" href="javascript:getText()">Go!</a> 
    </div>
</div>

From the button I tried this:

function getText(){
  alert($(this).parent().parent().children().text() );
}

This doesnt really work, I know there is a way! It's important to use $(this) for this time.

Edit: This is the whole Javascript:

<script>
   jQuery(document).ready(function($) {  
        $(".ptp-button").attr("href", "javascript:getText()");
  });
        function getText(){
            alert($(this).closest('.ptp-item-container').find('.plan').text());
        }
</script>

But the console says "Uncaught TypeError: undefined is not a function VM4092:1(anonymous function)"

Dont I have to give $(this) as an argument on javascript:getText($(this)) or something like this?

You shouldn't be targeting it with javascript: href. Instead, use an .on() handler, that is the correct way to handle the click event on JQuery. Then you'll be able to use the this reference:

Then, as already answered, instead of navigation through the parents, use the .closest() function:

$('.ptp-item-container').on('click', '.button', function() {
    alert($(this).closest(".ptp-item-container").find(".plan").text());
});

You can use a combination of .closest() and .find() :

alert($(this).closest(".ptp-item-container").find(".plan").text());

It pays to spend some time browsing the jQuery API documentation.

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