javascript - jquery .html() VS innerHTML()

标签 javascript jquery innerhtml

这里的人建议我使用 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/

相关文章:

javascript - 使用 csv-parse 和 Node 在读取和解析文件中添加快速随机访问

javascript - 单击按钮时,不会引发 OnClientClick 事件

javascript - 无法使用 jquery ajax 发布数据

javascript - 添加或删除文本框,然后使用 PHP 或 Jquery 获取其值

javascript - 如何使用 AJAX 调用 innerHTML 中的 PHP 值

javascript - TypeError : The first argument must be one of type string, 缓冲区、ArrayBuffer、数组或类似数组的对象。在cryptoJS中接收到类型对象

javascript - 在 Three.js 中单击对象或 Sprite 时如何获取位置?

Javascript 故障更新输入值

javascript - ajax innerHTML 结果不从 PHP 返回 html 代码

javascript - insidehtml 中的警报按钮