根据not null将元素添加到文档OR元素

Adding element to document OR element depending on not null

本文关键字:元素 文档 OR 添加 根据 null not      更新时间:2023-09-26

很难将一个元素添加到另一个元素中。我的方法很独特。基本上,用户要么输入选择器,要么默认为文档。

所以我们有两个按钮,一个指定选择器,另一个不指定选择器。

<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传递到作用域中。请问,解决这个问题的正确方法是什么?

默认范围应该是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);
}

演示:Fiddle

尝试:

function createElementIn(scope){
    $('<div/>').css({
        position: "absolute",
        left: "500px",
        bottom: "500px",
        display: "block"
    }).appendTo(scope);
}

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

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

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

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