gpt4 book ai didi

JavaScript/JQuery : innerHTML Not Working

转载 作者:行者123 更新时间:2023-12-03 02:17:43 25 4
gpt4 key购买 nike

我想更改<div id="homePagePosts">里面的内容是来自服务器的新数据。新数据在 HTML服务器呈现的格式。然而,在AJAX之后旧的HTML仍然保持不变。浏览器已收到数据。

当我 console.log如下所示,我可以看到渲染的新 HTML 数据显示在控制台中。我已将 Javascript 和 JQuery 文件放在 <body> 的底部。但仍然不起作用。我不太确定这里出了什么问题。

HTML

<div id="homePagePosts">
<% include ../ajaxSnippets/mainHome %>
</div>

Javascript

$.ajax({
url: "/main/home",
type: "POST",
contentType: "application/json",
data: JSON.stringify(sendData)
}).done(function(result){
//This shows up in the console
console.log(result)
updateMainPagePosts(result);
}).fail(function(err){
console.log(err);
});

var updateMainPagePosts = function(posts){
document.getElementById("homePagePosts").innerHTML = posts;
};

最佳答案

您已将函数定义为变量,并且在此方法中不可用。

更改此:

var updateMainPagePosts = function(posts){
document.getElementById("homePagePosts").innerHTML = posts;
};

对此:

function updateMainPagePosts(posts){
document.getElementById("homePagePosts").innerHTML = posts;
}

更多详细信息来自:https://www.quora.com/Is-the-var-x-function-the-same-as-the-function-x-in-JavaScript :

This will break. It uses a Function Expression which is being assigned to a variable. console.log(myFunction(1, 2)); var myFunction = function (a, b) { return a + b; };

This will print '3' to your console. It uses a Function Declaration. console.log(myFunction(1, 2)); function myFunction(a, b) { return a + b; }

The difference is that in the example with a function Definition, the function is being "hoisted" to the start of the scope (which could be a parent function, or the file, for example) by the JavaScript interpreter, which means anywhere within that scope it can be called and it will execute the function you have written.

In the function Expression the function is being passed around as if it were a value and is interpreted whenever it is asked to be. In the example we're seeing here, it, as a value is being assigned to the myFunction variable. Since we put a 'var' statement in front of that variable, then myFunction that variable is being hoisted, but its value, the function expression, is not hoisted (do not get the two confused).

关于JavaScript/JQuery : innerHTML Not Working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49294549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com