开发者

Use jQuery to Check if Link exist

I have a pagination div that contains links to the previous page <span id="previous"><a href="www.site.com/page/1" >Previous</a>, and to the next page. On the first page, there will not be any link to the previous page.

Now I have 2 image buttons with front and back arrows. If the user clicks on these buttons, jQuery will take the link from the pagination div as 开发者_StackOverflow社区mentioned above and redirect the user to these links. However if the pagination link does not exist like on the first page, clicking the previous button will not do anything.

My Code:

//img has id = info_rightclick_left

$("#info_rightclick_left").click(function() {
                    if($("#pagination_previous")) {
                        window.location  = $("#pagination_previous a").attr("href");
                    } else {
                        alert("NOO");
                    }
                });

The problem now is that it seems like whether or not #pagination_previous exists, clicking the image still redirects the user. In this case, on page 1, the user gets redirected to undefined

How can I solve this?


Try this.

$("#info_rightclick_left").click(function() {
                    if($("#pagination_previous").length) {
                        window.location  = $("#pagination_previous a").attr("href");
                    } else {
                        alert("NOO");
                    }
                });


the answer in your question itself! just check for undefined like so:

$("#info_rightclick_left").click(function() {
   if($("#pagination_previous a").attr("href") !== "undefined") {
      window.location  = $("#pagination_previous a").attr("href");
    }
});


if($("#pagination_previous").length > 0) {

jQuery returns a list of captured elements, if it doesn't find any it will return an empty list, but still a list

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜