i want to use js this function:
i have a string[] s={"11111","2222","33333",...} how to
achieve the html body
<h2>total s.length </h2>
<p>s[0]</p>
<p>s[1]</p>
<p>s[2]</p>
because s.length and content is uncertain,so i cannot one by one print,i want to use javascript,can you tell me how,i know little about js knowledge.thank you
var arr = ["11111","2222","33333"];
var output = "<h2>total " + arr.length + "</h2>" + "<p>" + arr.join("</p><p>") + "</p>";
document.getElementById("OutputPanel").innerHTML = output;
Live demo: http://jsfiddle.net/TQSK4/
You better add the result into existing container in the document, like in the example, not write directly to the document.
Related
I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
I've been following this tutorial on how to make JS widget. However I noticed that manually building html with plain JavaScript is not DRY. I am planning to build a form, tables etc. in a JS widget. Whats the best way to do this?
$.getJSON(jsonp_url, function(data) {
var fruits = ["Apples", "Mangoes", "Banana"];
var myHtml = "<ul>";
$(fruits).each(function(i){
myHtml += "<li>" + fruits[i] + "</li>";
});
myHtml += "</ul>";
$('#example-widget-container').html(myHtml);
});
if you want one of your divs or containers to continuously grow while you build dynamic content, without losing older content, use jQuery.append
$('#example-widget-container').append(myHtml);
this is probably the cleanest way. Or you can do other things like
var html = $('#example-widget-container').html();
newHtml = yourContent;
$('#example-widget-container').html(html + newHtml);
In JavaScript you can generate html content in different ways :
Create HTML with a string directly :
$("#sampleArea").append('<div class="' + newClass + '">' + newText + '</div>');
Create HTML with jQuery Api wrapping :
$("#sampleArea").append($('<div/>',{class : newClass}).text(newText));
Use a template engine in Javascript (like mustache.js) :
<script id="exampleTpl" type="x-tmpl-mustache">
<div class="{{class}}">{{text}}</div>
</script>
<script>
var data = {
class: newClass,
text: newText
}
var template = $('#exampleTpl').html();
var html = Mustache.render(template, data);
$('#sampleArea').append(html);
</script>
The best solution will depends of your use.
I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);
If i have
<p>someword here</p>
<span>another thing here</span>
<div id="text">other thing here</div>
<!-- any other html tags -->
How do I insert a space in first and last position of the content?
I want the result to be
<p> someword here </p>
<span> another thing here </span>
<div id="text"> other thing here </div>
<!-- after tags like <p> and before </p> there have one space -->
Naive (and incorrect!) example would be:
var victims = document.querySelectorAll('body *');
for( var i = 0; i < victims.length; i++ ) {
victims[i].innerHTML = " " + victims[i].innerHTML + " ";
}
But once you run it, you will find out that all your elements got destroyed! Because, when you are changing innerHTML, you are changing element children as well. But we can avoid that, by not replacing content, but adding it:
var padLeft = document.createTextNode( " " );
var padRight = document.createTextNode( " " );
victims[i].appendChild( padRight );
victims[i].insertBefore( padLeft, victims[i].firstChild );
Looks cool! But, o no - we ruin our script tags, images and so on. Lets fix that too:
var victims = document.querySelectorAll('body *');
for( var i = 0; i < victims.length; i++ ) {
if( victims[i].hasChildNodes ) {
var padLeft = document.createTextNode( " " );
var padRight = document.createTextNode( " " );
victims[i].appendChild( padRight );
victims[i].insertBefore( padLeft, victims[i].firstChild );
}
}
Here you got the script :) Its not cross-browser all the way down to Netscape4, but is enough to understand basic idea.
If you insist using JS + RegExp to pad every element's innerHTML then you could do:
var
r = /(<[^>]+>)(.*)(<\/[^>]+>)/g,
func = function(str) {
return str.replace(r, function(original, a, b, c) {
return a + ' ' + (r.test(b) ? func(b) : b) + ' ' + c;
});
};
func("<p name='somename'>someword here</p>");
// "<p name='somename'> someword here </p>"
func("<div>I have things here<span>And more here<p>And even more here</p></span></div>");
// "<div> I have things here<span> And more here<p> And even more here </p> </span> </div>"
This is just to show how you could do this, but I highly recommend against it. The examples I provide is extremely simple. Anything like a normal page (say, the one you are looking at now) has all sorts of tags. This would be extremely exhaustive. And not very wise.
For a single element (as you seem to be asking):
element.html(' ' + element.html() + ' ')
For every element on the page (as your example seems to indicate), apply that to each element.
With jQuery*:
$('#id').html(' ' + $('#id').html() + ' ');
If you know that the elements do not have nested elements, it would be better to use the simpler:
$('#id').text(' ' + $('#id').text() + ' ');
(*) The reason for using jQuery and not plain javascript is that browsers (I'm looking at you, IE), have different inbuilt properties for getting and setting these values. jQuery saves you from having to worry about that.
in your case:
$("*").html(function(index, html){ return " " + html + " "; });
I'm trying to add a piece of javascript code to a certain <div>.
I enclosed the code in pre and code tags, but when I actually run this the code gets executed. Obviously, that's not what I want at all.
var code = '<pre><code><script type="text/javascript" src="http://source.com/test.js"><\/script>\n';
code = code + '<script type="text/javascript">\n';
code = code + '\tadimp.id = ' + 1 + ';\n';
code = code + '\tadimp.type = ' + 1 + ';\n';
code = code + '\tadimp.generate();\n';
code = code + '<\/script></code></pre>';
$("#code").html(code);
You should use < and > for < and > in this case. Try this
var code = '<pre><code><script type="text/javascript" src="http://source.com/test.js"><\/script>\n';
code = code + '<script type="text/javascript">\n';
code = code + '\tadimp.id = ' + 1 + ';\n';
code = code + '\tadimp.type = ' + 1 + ';\n';
code = code + '\tadimp.generate();\n';
code = code + '<\/script></code></pre>';
$("#code").html(code);
Surprise! You just manufactured your own XSS vulnerability. Always HTML-encode any data you put into HTML. ("data" is anything you want to appear on screen.)
In the HTML DOM this is thankfully completely automatic. Just use the text property, not the HTML property.
var code = [
'<script type="text/javascript" src="http://source.com/test.js"><\/script>',
'<script type="text/javascript">',
'\tadimp.id = ' + 1 + ';',
'\tadimp.type = ' + 1 + ';',
'\tadimp.generate();',
'<\/script>'
].join('\n');
$('#code').text(code);
// --------^^^^
Live demo: http://jsfiddle.net/6qdBD/3/
Pre tags format the text not necessarily keep what the text within them from being executed as html. Or in this case JavaScript. A better method would be to replace < and > with the html entities < and >.
Instead of using the < and > symbols use < and >
var code = '<script type="text/javascript" src="http://source.com/test.js"></script>\n'
I suggest to just simply replace the < in <script tag to '< and at the end to '>.
Since HTML tags are permitted inside PRE, you cannot just "insert" a text file into an HTML document by slapping <PRE> and </PRE> around them. You have to convert the &, < and > characters into entities first.
From http://htmlhelp.com/reference/wilbur/block/pre.html