简体   繁体   中英

jquery .html() VS innerHTML()

People on here are recommending that I use jQuery, but when I changed the code to jQuery and used .html() it is like it did nothing. I even removed half of the html code that needed to be added as someone suggested I was asking way to much of innerHTML and HTML.

In Simple task, all I want is for when a user click on the DIV that it runs the onClick event.

 html += "<div onClick='loadnewsstory();' class='news'> this is a test story, for this test story we are not getting data from JSON</div>";

I have tried both

$("#activecontent").html(html);
document.getElementById("activecontent").innerHTML

The problem I have is relating to the following code.

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>";


    }
}

you will see in this area i have a link

<a href='javascript:loadnewsstory();'>" + news.post_title + "</a>

it suppose to fire

function loadnewsstory()
{
    navigator.notification.alert(device.uuid);
}

but I am not getting that fire.

Yes this is a web app for iOS and Cordova but I believe this is a javascript issue.

Don't use += , as it is used in an improper instance and returns an "unexpected token" error because var html was not previously equal to anything. I removed it and it appeared to fix the problem. Fiddle

If you must use += set var html = $("#activecontent").html() , then you may afterwards use += when you re-define the variable ( Fiddle 2 )

If your structure looks like

html

<div id="activecontent">
  <div class='news'>Story 1</div>
  <div class='news'>Story 2</div>
</div>

and you want each div.news to by dynamic and clickable, you could do that like this with jQuery

javascript

$(function(){
  $("#activecontent").on('click', '.news', function(){
     //You clicked the div 
     console.log( 'Clicked', $(this) );
  });
});

And if you want to append divs to your #activecontent with an ajax request. Let's assume your JSON looks like

json

[
  { "id": 1, "content": "My first story" },
  { "id": 2, "content": "Another one" },
  { "id": 3, "content": "Last story" }
]

Your javascript to load that could look like

javascript

$.getJSON( "http://url_of_json.json", function(result){
   for(var i in result){
      $("#activecontent").append( $("<div>").addClass('news').html(result[i].content) );
   }
});

alternative javascript for the ajax which is faster on the DOM

$.getJSON( "http://url_of_json.json", function(result){
   var newHtml = "";
   for(var i in result){
     newHtml += "<div class='news'>" + result[i].content + "</div>";
   }
   $("#activecontent").append( newHtml );
   // Or $("#activecontent").html( newHtml );
   // if you want to replace what the page loaded with
});

Now to explain. The first piece of javascript with the .on , what were doing there is binding an event listener to your parent div, #activecontent . We do that because it will always exist in your page. You will be adding and maybe removing divs from that container based on your AJAX call, so instead of having to bind a click (or inline some javascript for every div), you can bind once to the parent, and then delegate that click to '.news'. You can alternatively bind the click to each new div, but delegating is cleaner.

As for the part about loading the JSON and writing it. If you are going to add some stuff to a node's innerHTML, the jQuery way is to use .append() . It's just a shortcut to something like

//vanilla js way
var e = document.getElementById('myThing');
e.innerHTML = e.innerHTML + "Thing I want to append";
// vs jQuery way
$("#myThing").append("Thing I want to append");

//To continue this example, to replace your myThing's html
//vanilla
e.innerHTML = "my new html";
//jQuery
$("#myThing").html("my new html");

Hopefully this clears things up for you. If you are just jumping into jQuery, know that it's not always that it's faster to write than the vanilla javascript, but rather that when you do something like ..html('new stuff'); , it's going to use a method that works best with all browsers. So if there's some rogue version of IE out there than wants to use .innerHTMLmsIsNeat instead of .innerHTML , jQuery will sort that for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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