【问题标题】:Dynamic element manipulation with jQuery使用 jQuery 进行动态元素操作
【发布时间】:2018-02-16 10:30:14
【问题描述】:

我有一个由 jquery fonticonpicker 动态创建的元素。 我正在尝试操作图标,但简单地使用下面的代码是行不通的。 .icons-selector i 由插件动态创建。

我总是成功地操作一个元素,只需要从一个已经存在的元素开始编写我的选择器,即:body 或 document。有人可以提供一些简单的替代方案来解决这个问题吗?

目标是我需要在加载后修改元素。无需用户操作。

$(document).ready(function(){
    iconContainerID = "id_12";
    $('body #' + iconContainerID).css('background', 'red'); // this works!

    $('body #' + iconContainerID + ' .icons-selector i').css('background', 'yellow'); // this doesnt work
});

只有当我在页面上创建了另一个元素并向它添加了一个单击事件,然后单击它时.. 它最终会设置样式

这行得通:

<a href="" id="clickme">click me</a>

$(document).on('click', '#clickme', function(){
    iconContainerID = "id_12";
    $('body #' + iconContainerID + ' .icons-selector i').css('background', 'yellow'); // this does work
});

【问题讨论】:

  • 在您的插件完成创建动态元素后,您是否保留了此代码。
  • @ManojYadav 是的,我确实想到了这一点,并在插件代码运行后放置了代码。但是 document.ready 不应该等待整个加载吗?
  • 是的,但如果你的插件也等待 document.ready() 函数怎么办。 document.ready 等待 DOM 创建而不是 dom 操作的任何方式。在这种情况下,您的图书馆正在被操纵,所以请尝试一下。

标签: javascript jquery dom dynamic


【解决方案1】:

这不是一个好的解决方案。不过,如果您没有其他解决方法,请使用它。

此方法使用一个 intervel 函数来检查元素是否存在 添加添加 css 时可用。一旦元素可用,intervel 函数就会被清除。

注意:假设您将始终呈现图标(异步)。否则我们需要防止无限间隔执行。

$(function() {
  AppendAfter5Secs();
  AddRequiredCssAfterLoading();
});

function AppendAfter5Secs() {
  setTimeout(function() {
    var div = $('<div id="id_12">');
    div.append($('<div class="icons-selector"><i>Myicon</i><div>'));
    $('#dvContainer').append(div);
  }, 5000);
}

function AddRequiredCssAfterLoading() {
  var iterationCount = 1;
  var Intr = setInterval(function() {
    console.log(iterationCount++);
    var iconContainerID = "id_12";
    if ($('body #' + iconContainerID + ' .icons-selector i').length > 0) {
      $('body #' + iconContainerID + ' .icons-selector i').css('background', 'yellow');
      clearInterval(Intr);
    }
  }, 1000);
}
#id_12 {
  width: 80px;
  height: 50px;
  background: red;
}

.icons-selector i {
  width: 30px;
  height: 30px;
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dvContainer">

</div>

【讨论】:

    【解决方案2】:

    这是因为在 document.ready 上元素不在 DOM 中。

    试试:

    $('body #' + iconContainerID + ' .icons-selector i').load(function(element) {
       $(element).css('background', 'yellow');
    });
    

    当元素被加载并准备好被修改时,这将应用 css 修饰符。 请参阅文档:https://api.jquery.com/load-event/

    【讨论】:

    • 感谢 Marcal,但从我正在阅读的内容来看,该功能在 1.8 中似乎已被弃用。也试过了,还是不行。
    • 检查这个话题,也许一些建议适用于你的情况:stackoverflow.com/questions/6386128/…
    猜你喜欢
    • 2014-12-02
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多