在 jQuery 中将对象作为函数参数传递

发布于 2024-11-03 11:56:43 字数 1286 浏览 1 评论 0原文

我试图将 JSON 元素传递给函数,但它不起作用。有什么想法吗?这是我的代码:

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "/smallbusiness/_assets/js/events.json",
        success: formatJson,
        error: function() {
            alert("Data file failed to load");
        }
    });
});

function formatJson (data) {

        var json = data.events.event;
        var containerList = $('#event-list');
        var containerDescrip = $('#event-descrip');
        var template = '';
        var defaultDescrip = '';

        //Format and display event list 
        $.each(json, function(i, item) {
            template += '<p><a href="javascript:void(0)" onClick="formatDescrip(' + i + ',' + json[i].title + ')">' + this.title + '</a></p>';
        });
        containerList.html(template);
}

function formatDescrip(j, jsonData) {
    alert(j);
    alert(jsonData);
}

我试图将 ijson[i].title 传递给 formatDesrip() 但它抛出此错误:

Error: missing ) after argument list
Source File: http://localhost/smallbusiness/webinars.html#
Line: 1, Column: 20
Source Code:
formatDescrip(3,How to Leverage Email Marketing)

我做错了什么?如果我想传递整个 json 对象怎么办?我该怎么办呢?看起来应该很简单,但我不断收到错误。

I am trying to pass a JSON element to a function, but it's not working. Any thoughts? Here is my code:

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "/smallbusiness/_assets/js/events.json",
        success: formatJson,
        error: function() {
            alert("Data file failed to load");
        }
    });
});

function formatJson (data) {

        var json = data.events.event;
        var containerList = $('#event-list');
        var containerDescrip = $('#event-descrip');
        var template = '';
        var defaultDescrip = '';

        //Format and display event list 
        $.each(json, function(i, item) {
            template += '<p><a href="javascript:void(0)" onClick="formatDescrip(' + i + ',' + json[i].title + ')">' + this.title + '</a></p>';
        });
        containerList.html(template);
}

function formatDescrip(j, jsonData) {
    alert(j);
    alert(jsonData);
}

I am trying to pass both i and json[i].title to formatDescrip() but it's throwing this error:

Error: missing ) after argument list
Source File: http://localhost/smallbusiness/webinars.html#
Line: 1, Column: 20
Source Code:
formatDescrip(3,How to Leverage Email Marketing)

What am I doing wrong? And what if I wanted to pass the entire json object? How would I go about that? It seems like it should be straightforward, but I keep getting errors.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

〆一缕阳光ご 2024-11-10 11:56:43

您忘记了标题周围的引号。

    $.each(json, function(i, item) {
        template += '<p><a href="javascript:void(0)" onClick="formatDescrip(' + i + ',\"' + json[i].title + '\")">' + this.title + '</a></p>';
    });

然而,为什么不使用 jQuery 的“.delegate()”而不是这样设置处理程序呢?

    $.each(json, function(i, item) {
        template += '<p><a class="dynamic" data-index="' + i + '" href="#">' + this.title + '</a></p>';
    });
    containerList.delegate("a.dynamic", "click", function(ev) {
      formatDescrip($(this).data('index'), $(this).text());
    });

或者类似的东西;如果列表被扩展多次,那么“.delegate()”调用可能应该在处理程序之外执行一次。

编辑 - 如果“formatDesrip()”函数需要访问原始“事件”对象(无论您用来创建列表的那些东西是什么)标签),您可以将其传递给“formatDesrip()”而不是索引,然后根据需要修改其他函数:

    containerList.delegate("a.dynamic", "click", function(ev) {
      formatDescrip( json[$(this).data('index')] );
    });

    // ...

function formatDescrip(eventObj) {
    alert(eventObj.title);
    //
    // ... more code here ...
    //
}

You forgot the quotes around the title.

    $.each(json, function(i, item) {
        template += '<p><a href="javascript:void(0)" onClick="formatDescrip(' + i + ',\"' + json[i].title + '\")">' + this.title + '</a></p>';
    });

Instead of setting up the handlers that way, however, why not use jQuery's ".delegate()"?

    $.each(json, function(i, item) {
        template += '<p><a class="dynamic" data-index="' + i + '" href="#">' + this.title + '</a></p>';
    });
    containerList.delegate("a.dynamic", "click", function(ev) {
      formatDescrip($(this).data('index'), $(this).text());
    });

Or something like that; if the list is extended multiple times then the ".delegate()" call should probably be done once, outside the handler.

edit — if the "formatDescrip()" function needs access to the original "event" object (whatever those things are that you use to make the list of <a> tags), you can pass it in to "formatDescrip()" instead of the index, and then modify the other function as necessary:

    containerList.delegate("a.dynamic", "click", function(ev) {
      formatDescrip( json[$(this).data('index')] );
    });

    // ...

function formatDescrip(eventObj) {
    alert(eventObj.title);
    //
    // ... more code here ...
    //
}
岁吢 2024-11-10 11:56:43

我已经在评论中解释了问题是什么(缺少引号)。

但最好不要以这种方式创建 HTML,而是创建“真实”元素。使用 jQuery 更容易:

var $div = $('<div />');
//Format and display event list 
$.each(json, function(i, item) {
    var title = json[i].title;
    $('<p />').append(
        $("<a />", {
            href: "javascript:void(0)", // you should use a proper URL here
            text: title,
            click: function(e){
                e.preventDefault(); 
                formatDescrip(i, title);
            }
        })
    ).appendTo($div);
});
containerList.empty().append($div.children());

更新: 或者甚至更好,使用 .delegate() 作为 @Pointy 建议

I already explained in my comment what is the problem (missing quotes).

But it is better to not create the HTML this way, but to create "real" elements. It is even easier with jQuery:

var $div = $('<div />');
//Format and display event list 
$.each(json, function(i, item) {
    var title = json[i].title;
    $('<p />').append(
        $("<a />", {
            href: "javascript:void(0)", // you should use a proper URL here
            text: title,
            click: function(e){
                e.preventDefault(); 
                formatDescrip(i, title);
            }
        })
    ).appendTo($div);
});
containerList.empty().append($div.children());

Update: Or maybe even better, use .delegate() as @Pointy suggests.

葬心 2024-11-10 11:56:43

我认为也许您的标题中有一个简单的引用,这会破坏您的代码。尝试对字符串中的这些字符进行转义或使用双引号而不是简单的引号。

I think that maybe you have a simple quote as part of the title and that is breaking your code. Try to scape those characters in your string or using double quotes instead simple ones.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文