【发布时间】:2013-09-01 00:56:11
【问题描述】:
很难将一个元素添加到另一个元素中。我的方法是独一无二的。基本上用户要么输入一个选择器,要么默认它是文档。
所以我们有 2 个按钮,一个指定选择器,一个不指定。
<button onClick="callFunction({where:'#test'})"> Test selector</button>
<button onClick="callFunction()"> default</button>
和函数“callFunction”:
function callFunction(arguments){
scope= (arguments.where===undefined? $(document) : $(arguments.where));
createElementIn(scope);
}
然后调用createElementIn(scope)函数并在给定的选择器中创建元素
function createElementIn(scope){
var newdiv = document.createElement('div');
$(newdiv).css("position", "absolute");
$(newdiv).css("left", "500px");
$(newdiv).css("bottom", "500px");
$(newdiv).css("display", "block");
newdiv.innerHTML = str;
scope.append(newdiv);//Over here, it does not append
}
我有一种感觉,我混淆了何时做 $(scope)... 以及何时离开它... document.body.appendChild 有效,但我无法将 document.body 传递到范围内。 请问,解决这个问题的正确方法是什么?
【问题讨论】:
-
如果你使用 jQuery,不要使用
createElement,使用$('<div/>'),不要使用innerHTMl,而是html(str)
标签: javascript jquery append document appendchild