开发者

javascript click event question

I have a question below is a list with the anchor links now when the links are clicked I dont want the browser to go to that web page instead I want the browser to stay on the current page and display the list in a开发者_如何学Pythonn alert box to the user. I know this can be done with javascript maybe with the onclick event on the list item and display an alert box but how do I stop the browser to go that webpage.

 <ul id='list_o_links'>
    <li><a href='http://www.google.com'>List Item1</a></li>
    <li><a href='http://www.yahoo.com'>List Item2</a></li>
    </ul> 


You stop the browser from going to the link destination by calling event.preventDefault() or returning false in the bound event handler. I think the first is more explicit:

var alert_instead_of_following_link = function (event) {
    event.preventDefault();
    alert(this.href);
};

$("#list_o_links a").bind("click", alert_instead_of_following_link);


$("#list_o_links").children().click(function () {
    var list = [];

    $.map($("#list_o_links").children(), function (elem) {
        list.push($(elem).text()); // take the text of each list item
    });

    alert(list.join(', '));

    return false; // stop the browser from going to the link
});

jsfiddle example

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜