jQuery / Javascript:自动填充动态填充的元素 [英] jQuery/Javascript: Autopopulate Dynamically Populated Elements

查看:76
本文介绍了jQuery / Javascript:自动填充动态填充的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在尝试自动填充动态填充的元素(例如选择输入)。问题是由于AJAX的异步性引起的,所以我需要一些等待线程完成。



我试图实现一个 while 循环使用setTimeout(0),但没有按预期方式进行。

I am trying to auto-populate dynamically populated elements (eg select inputs). The problem is caused due to the asynchronicity of AJAX, so I need some sort of "wait until thread is complete".

I've attempted implementing a while loop with a setTimeout(0), but that did not go as expected.



演示






Demo



http://jsfiddle.net/vol7ron/wQZdM/


http://jsfiddle.net/vol7ron/wQZdM/



条件






Conditions




  1. 不能 / strong>编辑源代码,因为这应该是一个自动填充表单进行测试的工具。

  1. I cannot edit the source code, since this is supposed to be a tool to auto-populate forms for testing.



推荐答案

你应该使用 MutationObserver 来处理这个。观察所有选择元素以备将来更改。

You should use MutationObserver to handle this. Observe all the select elements for future changes.

这是更新的小提琴

基本上这是我如何更改它:

Basically here's how I changed it:

var observer  = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        handleSelect(mutation.target);
    });
});
$('select').each(function () {
    observer.observe(this, { childList : true }); // We observe the elementw
    handleSelect(this);
});

function handleSelect(el) {
    var t = $(el);
    var c = t.children('option');

    t.val(c.eq(1).val()); // set value to second option value
    t.trigger('change'); // calls the onChange even if it doesnt exist
}

请注意, MutationObserver 仅在现代浏览器中可用。您可以使用以下任何一个垫片/ pollyfills(它们各自具有不同的浏览器支持,所以选择所需的):

Note that MutationObserver is available only in modern browsers. You can use either of the follwoing shims/pollyfills(they each have different browser support, so choose the one you need):

  • https://github.com/megawac/MutationObserver.js
  • https://github.com/Polymer/MutationObservers

但这可能是测试工具的鬼祟。一般来说,我从硒或casperjs的经验,我只是等待新的选项到达,然后选择该选项。

But this might be kind of sneaky in testing tools. Generally with my experience from selenium or casperjs, I just would wait for the new options to arrive then select that option.

这篇关于jQuery / Javascript:自动填充动态填充的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆