[英]JQuery append to variable element
I am building my own JS library backed by jquery.我正在构建由 jquery 支持的自己的 JS 库。 The constructor starts building on top of an existing div to flesh it out.
构造函数开始在现有 div 之上构建以充实它。 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):
在库中,我正在调用 ajax,所以我知道如何附加到这个初始 div(这是传入的初始 div):
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".所以现在我需要循环并将元素附加到变量“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. 它不起作用,因为
sdiv
与t
变量相同,因为append
返回最初选择的元素。
Instead, create the ul
in it's own variable, then use that reference when appending. 而是在自己的变量中创建
ul
,然后在附加时使用该引用。 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. 请注意,我还裹着
this
在一个jQuery对象。 Assuming this code is being executed in an event handler, you would need to do that. 假设此代码正在事件处理程序中执行,则需要这样做。
@RoryMcCrossan has provided a great answer. @RoryMcCrossan提供了一个很好的答案。 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
: 然后最后将
$sdiv
附加到$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?如何修改这个脚本,这样当你点击错误的符号(例如字母)时它不会删除以前的符号,以及如何使“+”符号在你输入“+61”时只允许一次然后被禁止?
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.