usually I use the following form of code to display html elements with their data
<div id="parent">
<span>loading...</span>
</div>
<script>
var data="im data";
$("#parent").html(`<span>${data}</span>`);
</script>
but it is very inconvenient I have to write the span element twice and it will be very inconvenient if there are elements that need to be changed, so I want to fetch the element first instead of writing it back
so I want to fetch the element first instead of writing it back,
and code look like this
<div id="parent">
<span>${data}</span>
</div>
<script>
var data="im data";
$("#parent").html($("#parent").html());
// it displayed ${data} not im data
</script>
but it doesn’t produce as I expected
2
Answers
In your code you are writing
in your html file which will show as normal text
if you want to show some data in the span instead of
${data}
you can use
and if you want to fetch the html first then use
if you want to add more data in your parent div then
i think this will help to understand how jquery works
Here is a way of setting up a very simple templating engine:
However, it is not capable of nesting
${...}
elements and can only reference simple values from a given objectD
.The action is mainly done by a
.replace
callback function. The second argumentn
of that function contains the content of the first search group and this is then used to look up the actual content fromD
.There is another way of doing it using
eval()
, although this is usually shunned by the JavaScript programming community for "security reasons".eval()
will evaluate everything it is given as an argument, so this might incriminate the security and integrity of your page. Make up you own mind about it.