Get the href value of a previous HTML anchoer, <a>, using jQuery

纵饮孤独 提交于 2019-12-25 05:28:16

问题


I am trying to get the value of href of <a> that is the previous element to my current button that is clicked. How do I get it?

Here is my code.

HTML:

<a href="#activityNotes[0].noteText">
    <input value="Add Another" name="addAnotherNote" type="submit" class="addAnother secondary" onclick="addAnotherNote();"/>
</a>

jQuery:

$(".addAnother").click(function() {
    var jump = $(this).prev("a").attr("href");
});

When I try running this, I get

jump value undefined.

Why is this happening? Is it because I'm trying to get an anchor with # in front?

http://jsfiddle.net/5Twfc/2/

Actually I am trying to get the display to anchor section with name/id = activityNotes[0].noteText when I click on the add button. That is the reason I have this input button inside the <a>. Also, I am doing a form submit after I run few scripts.

$(".addAnother").click(function() {
    var jump = $(this).parent().attr("href");
    var new_position = $('#'+jump).offset();
    window.scrollTo(new_position.left,new_position.top);
    return false;
});

回答1:


Your a encloses input. prev gets previous sibling. In this case, you need to get the parent. Here's what will work based on your jsFiddle:

$(".addAnother").click(function() {
    var jump = $(this).parent().attr('href');
    $('#printJumpValue').text('' + jump);
})

and a live example:

  • http://jsfiddle.net/5Twfc/4/



回答2:


To get the value of href try to use this

    $('a').attr('href');



回答3:


The prev function gets the previous sibling. You want the parent item:

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



回答4:


That's because this points to the input. To get the anchor either move the class to it or use the following:

$(this).parent().prev("a").attr("href")


来源:https://stackoverflow.com/questions/9779833/get-the-href-value-of-a-previous-html-anchoer-a-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!