Jquery problem with appending and binding in the same time

我是研究僧i 提交于 2019-12-11 23:14:25

问题


I'm working on a fine rolldown select solution for my website.
I made an <a name="iwanthereanid" class="popper">Click Here!</a> link.
By clicking on it I call a popup() function.

$(".popper").click(function() {
    popup($(this));
});

In the popup() function i check was this already opened? No?
Lets make a div and fill it with things by fillwiththings().

function popup(where) 
{
    if (where.hasClass("on")) 
    {
        where.removeClass("on");
        where.next("div").remove();
    }
    else 
    {
        where.addClass("on");
        fillwiththings(where);
    }
}

function selectclose(where)
{
    var nameval = $(this).attr("name");
    var textval = $(this).text();
    where.attr("name", nameval);
    where.text(textval);
    where.removeClass("on");
    where.next("div").remove();
}

function fillwiththings(where, id)
{
    $container = $('<div class="popup"></div>')
    for (i = 0; i < object.length; i++)
    {
        $container.append($('<a name="'+jsonobject[i]["id"]+'">'+jsonobject[i]["name"]+'</a>').bind("click", {where: where}, selectclose()));
    }
}

In fillwiththings() I'd like to bind to the appended <a></a> an another function with the where parameter, to close, and replace the a(Click Here!) tag's text and name value. But the bind fails. What did i missed? Please help in this.

Thank you.


回答1:


You are not accessing the where parameter correctly. The event data is not passed as parameter to the event handler, it is a property of the event object:

function selectclose(event) {
    event.data.where
        .attr("name", $(this).attr("name"))
        .text($(this).text())
        .removeClass("on")
        .next("div").remove();
}

The other problem is that you pass the return value of selectclose() to bind. You have to pass the function directly:

$container.append($(...).bind("click", {where: where}, selectclose));
//                                          no parenthesis ------^


来源:https://stackoverflow.com/questions/5434719/jquery-problem-with-appending-and-binding-in-the-same-time

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