简体   繁体   中英

click event fired more than once ( supposed to be once)

this is my first post, here I wanted to create a chrome extension, when it is pressed, it will show links which can be pressed, links retrieved using AJAX. It worked so far, the only problem is when it is clicked on any link, sometimes it appeared twice or even thrice. can anyone give an explanation and answer to this problem?

Thank you!

var links = [];
links.push("http://www.tenmanga.com/book/rss/id-16896.xml");
links.push("http://mangafox.me/rss/fairy_tail.xml");
links.push("http://feeds.feedburner.com/9gag?format=xml");

Function Start()

function start(){
    for (var i in links)
        getXML(links[i]);
    $(document).ready(function(){
    });


}

Function getXML

function getXML(url){
    var test = $.ajax({
        type: "GET",
        url: url,
        dataType: "xml",
        success: function(xml){
            parse(xml);
bind();
        }
    });
    return test;
}

function bind(){
    $("a").click(function(e){
        chrome.tabs.create({url:$(this).attr("href")});
    });
}
function parse(xml){
    //$("#content").append();
    var title = $(xml).find('title').first().text();
    var createClickHandler = function(arg){
        return function(){ 
            open_item(arg); 
        };
    }
    $("#content").append(title+"<br>");
    $(xml).find('item').each(function(){
        var temp = document.createElement("a");
        var title = this.childNodes[1].textContent;
        var link = this.childNodes[3].textContent;
        temp.innerHTML = title;
        temp.setAttribute("href",link);
        $("#content").append(temp);
        $("#content").append("<br>");
    });
    $("#content").append("<br>");
}

START HERE!

var start = start();

The only reason to invoke click event more than once when clicked on an elements is, more than one event handler is registered over that. Each time you call bind what u have done is binding to event to 'a' so i guess for the first link it event is fired once for the seconds twice and for the third thrice.May be instead of using just $('a') that attributes to all the 'a' element in the page you may dynamically make 'a' with separate ids. That must end the weird behavior.

Invoke e.preventDefault(); where e is event in your click callback so that event won't bubble up and won't trigger anything else.

Also bind() should not be called on each success after ajax returned.

instead of binding on each link, do the following once:

$(document).on('click','a'
    function(e){
        chrome.tabs.create({url:$(this).attr("href")});
        return false;
    }
);

if you have no other anchors on link

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