0

Having a hard time adding an element into another element. my approach is unique. basically the user either enters a selector or by default it is the document.

so we have 2 buttons, one which specifies a selector and one which does not.

<button onClick="callFunction({where:'#test'})"> Test selector</button>
<button onClick="callFunction()"> default</button>

and the function "callFunction":

function callFunction(arguments){
    scope= (arguments.where===undefined? $(document) : $(arguments.where));
    createElementIn(scope);
}

then calls the createElementIn(scope) function and creates the element in the selector given

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

}

I have a feeling im mixing up when to do $(scope)... and when to leave it scope... document.body.appendChild works but i cant pass document.body into the scope. please, whats the right approach to solving this?

4

3 回答 3

1

默认范围应该是body元素 - 不是文档,由于元素的绝对定位,元素也不可见。

您混合使用了原生和 jQuery,我已将其更新为 jQuery 解决方案 - 您可以向该.css({...})方法添加其他样式

function callFunction(params){
    var scope= ($.isPlainObject(params) && params.where) ? $(params.where) : $('body');
    createElementIn(scope);
}
function createElementIn(scope){
    var newdiv = $('<div />', {
        html: 'some content'
    }).css({
        //position: 'absolute',
        display: 'block',
    })
    scope.append(newdiv);
}

演示:小提琴

于 2013-08-31T16:56:11.830 回答
0

尝试:

function createElementIn(scope){
    $('<div/>').css({
        position: "absolute",
        left: "500px",
        bottom: "500px",
        display: "block"
    }).appendTo(scope);
}
于 2013-08-31T16:51:14.273 回答
0

您正在将 jQuery 与本机 javascript 混合。只使用 jQuery 以避免误解。

我遇到了在 jquery 选择器之前使用 $ 前缀的做法,例如你可以这样写:

var $scope = (arguments.where===undefined? $(document) : $(arguments.where));
...
$scope.append(newdiv)

在这种情况下,您将知道,您不需要像这样 $($scope) 用 jQuery 包装 $scope

于 2013-08-31T16:52:12.837 回答