I am building my own JS library backed by jquery. The constructor starts building on top of an existing div to flesh it out. In the library I am making an ajax call, so to this initial div I know how to append like (where this is the initial div passed in):
var t = this;
var sdiv = t.append("<ul class='foo'></ul>");
So now I need to loop through and append elements to the variable "sdiv". For some reason
$(sdiv).append("<li class='bar'>" + element[i] + "</li>");
isn't working/rendering. How do you append elements to other elements created as variables?
Thanks
It's not working because sdiv
will be the same as the t
variable, as append
returns the originally selected element.
Instead, create the ul
in it's own variable, then use that reference when appending. Try this:
var $t = $(this);
var $sdiv = $('<ul />', { class: 'foo' }).appendTo($t);
// in your loop...
$('<li />', { class: 'bar', text: element[i] }).appendTo($sdiv);
Note that I also wrapped this
in a jQuery object. Assuming this code is being executed in an event handler, you would need to do that.
@RoryMcCrossan has provided a great answer. Another approach could be as follows:
var $t = $(this)
var $sdiv = $('<ul class="foo"/>');
Then in your loop do the following:
$sdiv.append( $('<ul class="bar"/>').text( element[i] ) );
Then finally append $sdiv
to $t
:
$t.append( $sdiv );
how to modify this script, so it doesn't delete the previous symbols when you click the wrong symbols ( letters for example), also how to make the "+" symbol to be allowed only once when you type it for "+61" and after that to be forbidden?
thank you again
<script>
$("#mobph").on('keyup', function(){
var n = $(this).val().replace("+61", "0").replace(/[^+][^0-9]+/, "");
//var n = $(this).val().replace(/[^0-9]+/g, "");//(/\D/g,'')
$(this).val(n.append(n).toLocaleString());
//do something else as per updated question
//myFunc(); //call another function too
});
</script>
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.