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

问题描述



演示






Demo




条件






Conditions



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

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



推荐答案

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

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:自动填充动态填充的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 20:18