【问题标题】:Adding element to document OR element depending on not null根据不为空将元素添加到文档或元素
【发布时间】: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,使用$('&lt;div/&gt;'),不要使用innerHTMl,而是html(str)

标签: javascript jquery append document appendchild


【解决方案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);
}

演示:Fiddle

【讨论】:

  • 谢谢!非常具有描述性,您实际上用一块石头杀死了 2 只鸟(关于我遇到的另一个问题)
【解决方案2】:

试试:

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

【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 2011-12-22
      • 2013-03-22
      • 1970-01-01
      • 2016-06-21
      相关资源
      最近更新 更多