console.log(data)
var link
$listSelector = $("#top5CompaniesList") //Your list element
$.each(data.result, function(i, obj) {
$listSelector.append('<li>');
link = $('<a href="dashboard.php#companyInfo?'+obj.symbol+'">'+obj.symbol+'</a>').click(function(){
$('.nav-pills a[href=#companyInfo]').tab('show') ;
$('body').scrollTop(0);
$('#companySearchInput').val(obj.symbol);
$('#companySearchButton').click();
return false;
});
$listSelector.append(link);
$listSelector.append('<br> Otherdata: '+obj.otherdata+'</li>');
});
Using the code above I'm trying to add list items to a list that includes a link which I have custom behavior designed for. The behavior works, except that there's a line break on the page where each .append() call happens.I'd like the list item to appear as one unbroken line. I tried using both .wrap() and .wrapInner(), but those seem to replace the entire innerHTML of the list item. Honestly I know they're probably the solution but I can't seem to wrap my head around the logic. Any help or a push in the right direction is much appreciated.
The problem is here:
$listSelector.append('<li>');
// ...
$listSelector.append('<br> Otherdata: '+obj.otherdata+'</li>');
First some theory. You can't add partial HTML to the document. The web page itself doesn't consist of HTML. It consists of elements, and HTML is only a markup language that represents those elements and tells the browser how to build them. Appending an open <li>
element without closing it doesn't make sense in this perspective: you can't have half of an element in the DOM.
When you have $listSelector.append('<li>')
you're appending an entire <li>
element to the document. It's exactly equivalent to $listSelector.append('<li></li>')
. When you later have $listSelector.append('<br> Otherdata: '+obj.otherdata+'</li>')
it's exactly equivalent to $listSelector.append('<br> Otherdata: '+obj.otherdata+'<li></li>')
– the browser doesn't "remember" that there was an open <li>
tag earlier so it "fixes" the broken HTML.
The extra empty <li>
elements are what cause the layout to look broken.
To fix it, first make the <li>
element, then add its contents to it, and then append it to the parent:
link = $('<a href="dashboard.php#companyInfo?'+obj.symbol+'">'+obj.symbol+'</a>').click(function(){
$('.nav-pills a[href=#companyInfo]').tab('show') ;
$('body').scrollTop(0);
$('#companySearchInput').val(obj.symbol);
$('#companySearchButton').click();
return false;
});
$('<li>')
.append(link)
.append('<br> Otherdata: '+obj.otherdata)
.appendTo($listSelector);
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.