这里的人建议我使用 jQuery,但是当我将代码更改为 jQuery 并使用 .html()
时,它就像什么也没做。我什至删除了一半需要添加的 html 代码,因为有人建议我询问大部分的 innerHTML 和 HTML。
在简单任务中,我想要的只是当用户单击 DIV 时运行 onClick 事件。
html += "<div onClick='loadnewsstory();' class='news'> this is a test story, for this test story we are not getting data from JSON</div>";
我都尝试过
$("#activecontent").html(html);
document.getElementById("activecontent").innerHTML
我遇到的问题与以下代码有关。
function newsstories()
{
document.getElementById("activecontent").innerHTML = "<h1 class='newsheader'>Latest News</h1>";
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","http://test.com/?uri=loadnews",false);
xmlhttp.send();
var newsreponse = JSON.parse(xmlhttp.responseText);
for (var i = 0, len = newsreponse.length; i < len; ++i) {
var news = newsreponse[i];
if(i % 2 == 0){
cssclass = "even";
}
else
{
cssclass = "odd";
}
// alert(news.featured_image);
document.getElementById("activecontent").innerHTML = document.getElementById("activecontent").innerHTML + "<div class='news " + cssclass + "'><div class='newstitle'><div class='newstitlecolor' id='news_"+ countstory+"'><a href='javascript:loadnewsstory();'>" + news.post_title + "</a></div></div><div class='base' style='background: url('" + news.featured_image + "');'><img src='" + news.featured_image + "' style='width:100%; height:100%;'/></div></div>";
}
}
你会在这个区域看到我有一个链接
<a href='javascript:loadnewsstory();'>" + news.post_title + "</a>
它应该会开火
function loadnewsstory()
{
navigator.notification.alert(device.uuid);
}
但我没有得到那火。
是的,这是一个适用于 iOS 和 Cordova 的网络应用程序,但我相信这是一个 JavaScript 问题。
最佳答案
不要使用+=
,因为它在不正确的实例中使用,并返回“意外 token ”错误,因为var html
以前不等于任何内容。我删除了它,它似乎解决了问题。 Fiddle
如果您必须使用 +=
set var html = $("#activecontent").html()
,那么您可以随后使用 +=
当您重新定义变量 ( Fiddle 2 )
关于javascript - jquery .html() VS innerHTML(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19483381/