使用来自动态创建链接的参数调用函数

Call function with argument from dynamically create link

本文关键字:参数 调用 函数 链接 创建 动态      更新时间:2023-09-26

我正试图基于从服务器返回的JSON创建一个div网格。当我迭代对象时,我会像这样创建

getApps(function(data){
    var displayMode = "<? echo  $_GET['displayMode']; ?>";
    var appsDisplayedCounter = 0;
    for (var i = 0; i < data.length; i++)
    {
        var app = data[i];
        // check if we're interested in this app
        var shouldDisplay = (displayMode == 'hired' && app.hired == 1) || (displayMode == 'self' && app.hired == 0) || !displayMode;
        if (shouldDisplay)
        {
            var innerContent;
            var content = '<div class="AppContainer">';
            if (appsDisplayedCounter % 2 == 0)
            {
                innerContent = '<img class="SquareImage" src="'+app.imagePath+'"/>'
                <div class="AppContainerName AppContainerBottomSegment">'+app.name+'</div>';
            }
            else
            {
                innerContent = '<div class="AppContainerName">'+app.name+'</div>'
                <img class="SquareImage AppContainerBottomSegment" src="'+app.imagePath+'"/>';
            }
            content = content + innerContent + '</div>';
            // nest the content in a link
            content = '<a href="javascript:showDetailView('+app+')" id="'+app.name+'">' + content + '</a>';
            $(".MainContentContainer").append(content);
            // link handler
            //$('#'+app.name).click(function(){showDetailView(app.name); return false});
            // increment counter
            appsDisplayedCounter++;
        }
    }
});
function showDetailView(app)
{
    alert(app);
}
function getApps(completion)
{
    $.ajax({
    url:    '/Apps.php',
    success: function(data)
        {
            var appsJson = data['apps'];
            completion(appsJson);
        },
    async:   false
    });
}

我的问题是将app对象传递到我的函数中。单击div不会执行任何操作。

--编辑--

当我在创建标签后检查它时,它看起来像这个

<a id="AppName" href="javascript:showDetailView([object Object])">

我在showDetailView(app)中设置了一个断点,当我单击此链接时,该断点永远不会被调用。

您得到[object Object]是因为您将其作为字符串引用,但它不是字符串。

如果您试图将整个对象传递到函数中,那么您应该使用JSON.Stringify()

content = '<a href="javascript:showDetailView('+ JSON.stringify(app) +')"
                     id="'+app.name+'">' + content + '</a>';

然后在showDetailView功能中:

function showDetailView(app) {
    var appJSON = JSON.parse(app);
    alert(aJSON.name);
}

参考文献

  • JSON对象概述
  • JSON.stringify()
  • JSON.parse()