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

时间:2022-12-05 14:27:29

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

我试图将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);
}

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

我试图传递I和json[I]。formatdescripp()的标题,但是它会抛出这个错误:

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.

我做错了什么?如果我想传递整个json对象呢?我该怎么做呢?看起来应该很简单,但是我总是会出错。

3 个解决方案

#1


2  

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()"?

但是,与其以这种方式设置处理程序,为什么不使用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());
    });

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

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

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:

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

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

    // ...

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

#2


1  

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:

但是最好不要以这种方式创建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());

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

更新:或者更好,使用。delegate()作为@Pointy的建议。

#3


0  

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.

我认为你可能有一个简单的引用作为标题的一部分,那就是破坏你的代码。尝试在字符串中设置这些字符,或者使用双引号代替简单的引号。

#1


2  

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()"?

但是,与其以这种方式设置处理程序,为什么不使用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());
    });

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

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

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:

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

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

    // ...

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

#2


1  

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:

但是最好不要以这种方式创建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());

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

更新:或者更好,使用。delegate()作为@Pointy的建议。

#3


0  

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.

我认为你可能有一个简单的引用作为标题的一部分,那就是破坏你的代码。尝试在字符串中设置这些字符,或者使用双引号代替简单的引号。