在setInterval中替换

时间:2017-12-28 05:26:19

标签: javascript html setinterval

我希望每1000毫秒我的元素obj被我的函数myPlugin创建的新元素替换。

问题在于元素没有被替换。

我猜这个问题来自披露或类似的事情。在早上6点再懒得思考,我只想要一个答案:)

Plunker https://plnkr.co/edit/J9k6kFc0yWySXKFwBdB1?p=preview

脚本

<script type="text/javascript">
  $(function () {
    $('.myCrypto').each(function(i, obj) {
      window.setInterval(function() {
        var a = myPlugin(obj.getAttribute("cf_widget_size"), obj.getAttribute("cf_widget_from"), obj.getAttribute("cf_widget_to"), obj.getAttribute("cf_clearstyle"));
        obj.replaceWith(a);
      }, 1000);
  });
});

<div>
  <div class="myCrypto" cf_widget_size="large" cf_widget_from="BTC" cf_widget_to="usd" cf_clearstyle=true></div>
</div>

为myplugin

function myPlugin( cf_widget_size,  cf_widget_from,  cf_widget_to,  cf_clearstyle) {
    var t = document.scripts[document.scripts.length - 1],
        n = t.parentElement,
        r = document.createElement("iframe"),
        i = "https://www.worldcoinindex.com/widget/renderWidget?size=" + cf_widget_size + "&from=" + cf_widget_from + "&to=" + cf_widget_to + "&clearstyle=" + cf_clearstyle;
        if (cf_widget_size == "small") {
            r.width = "300px";
            r.height = "135px"
        } else if (cf_widget_size == "medium") {
            r.width = "300px";
            r.height = "240px"
        } else if (cf_widget_size == "large") {
            r.width = "300px";
            r.height = "340px"
        }
    r.id = "cf_widget_iframe"
    r.setAttribute("data-size", cf_widget_size);
    r.style.cssText = "border:none;"; -1 == navigator.userAgent.indexOf("MSIE") ? r.src = i : r.location = i;
    console.log("hahah");
    return (r);
  };

2 个答案:

答案 0 :(得分:0)

您必须将obj替换为新的a objcect

obj.replaceWith(a);
obj = a;

https://plnkr.co/edit/xqmepXXU9J86sPe0H76a?p=preview

答案 1 :(得分:0)

这里有几个问题 -

  1. setInterval位于$.each内。这种方式选择器只执行一次,然后期望setInterval中的元素每1000毫秒运行一次,这将在第一次迭代中被替换。
  2. myPlugin应该将类.myCrypto分配给它返回的元素,以便可以再次使用相同的类选择器选择它。
  3. cf_widget_size=large以及html中提到的其他属性应该重新分配给要返回的元素(iframe)。
  4. 检查这个小提琴我想说的是什么。 https://jsfiddle.net/nikhilgirraj/jv0h1gLm/

相关问题