简体   繁体   English

在函数内使用jQuery .append()?

[英]Use jQuery .append() inside a function?

I've been trying to call a function that appends html tags inside of pre-existing div tags like this: 我一直在尝试调用一个函数,该函数将html标记附加在预先存在的div标记内,如下所示:

function loadTextbox(jsonUrl,divId){
$.getJSON(jsonUrl, function(json) {
    alert('hello');
    $('#' + divId).append('<h2></h2>')
        .find('h').append(json.heading).attr(json.config.backgroundConfig)
        .find('h').attr(json.config.headingConfig).append(json.heading).parent()
        .find('p').attr(json.config.bodyConfig).append(json.body);
    })
}

This is a complex example but I haven't been able to get anything working where the append() function is inside any sort of other function. 这是一个复杂的示例,但是在append()函数位于任何其他函数内部的情况下,我无法正常工作。 I can append just fine straight from the .js but otherwise no luck. 我可以直接从.js追加内容,否则没有运气。 I also know for a fact that the json calls are working as I use an identical call and queries for a different function. 我还知道一个事实,即当我使用相同的调用并查询其他函数时,json调用正在工作。 Is there a problem with putting append() in a function? 将append()放在函数中有问题吗?

EDIT: Also a note, the above alert does not work as is. 编辑:另外请注意,上述警报无法按原样工作。 However if it is moved one line up (above the $.getJSON call it works fine. Maybe this is important? Also, I am calling the function directly below it in the same .js file like so: 但是,如果将它向上移动一行(在$ .getJSON调用上方,它可以正常工作。也许这很重要吗?此外,我在同一.js文件中的正下方调用该函数,如下所示:

loadTextbox("./json/textbox.json","text");

If your alert never shows up, when it is inside the function, then that means you're not receiving a response. 如果您的警报从不显示,则当它在函数内部时,表示您没有收到响应。

If you're using Firefox, use the Firebug plugin to see if an exception is thrown serverside. 如果您使用的是Firefox,请使用Firebug插件查看服务器端是否引发了异常。

You might want to check the docs: 您可能要检查文档:

jQuery.getJSON( url, [ data ], [ success(data, textStatus, jqXHR) ] ) jQuery.getJSON(url,[data],[success(data,textStatus,jqXHR)])

Which means: your callback is the 3e argument, not the 2nd. 这意味着:您的回调是3e参数,而不是第二参数。

-- edit -编辑

So what you want to do is: 因此,您要做的是:

$.getJSON(jsonUrl, '', function(json) {
  ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM