【问题标题】:How to fill a select element which is not embedded in a form with CasperJS?如何使用 CasperJS 填充未嵌入表单中的选择元素?
【发布时间】:2015-02-14 11:44:29
【问题描述】:

我的html代码是:

<div class="setting-control">
<select class="on-off" id="custom-cache-pref">
  <option value="">Default</option>
  <option value="byc">Bypass cache</option>
  <option value="basic">Basic caching</option>
  <option value="iqs">Ignore query string</option>
  <option value="agg">Aggressive caching</option>
  <option value="all">Cache everything</option>
</select>
</div>

我通常会使用 casperjs

this.fillSelectors('form[name="formName"]', { 
    'select[id="custom-cache-pref"]': 'byc'                     
}, false);

选择选项“byc”,但这次“select”元素没有嵌入到表单中!

在这种情况下我该如何选择它的值?

【问题讨论】:

  • this.fillSelectors('select.on-off']' 工作吗?
  • @skribe 不,它没有

标签: javascript html-select casperjs


【解决方案1】:

改编自我的回答here,您可以创建自己的函数,按值选择选项。这会更改可能不会触发 select onChange 事件的选定索引。

casper.selectOptionByValue = function(selector, valueToMatch){
    this.evaluate(function(selector, valueToMatch){
        var select = document.querySelector(selector),
            found = false;
        Array.prototype.forEach.call(select.children, function(opt, i){
            if (!found && opt.value.indexOf(valueToMatch) !== -1) {
                select.selectedIndex = i;
                found = true;
            }
        });
        // dispatch change event in case there is some kind of validation
        var evt = document.createEvent("UIEvents"); // or "HTMLEvents"
        evt.initUIEvent("change", true, true);
        select.dispatchEvent(evt);
    }, selector, valueToMatch);
};

casper.start(url, function() {
    this.selectOptionByValue('select#custom-cache-pref', "byc");
}).run();

备选方案 1

__utils__.fill()casper.fillForm()的代码来看,表单的选择器不一定是表单。可能是一个div:

this.fillSelectors('div.setting-control', { 
    'select[id="custom-cache-pref"]': 'byc'                     
}, false);

备选方案 2

如果这仍然不起作用,您可能需要专注于页面上下文中的选择元素并使用 PhantomJS'page.sendEvent() 发送上下键事件来更改值:

this.evaluate(function(){
    document.querySelector('select[id="custom-cache-pref"]').focus();
});
this.page.sendEvent('keypress', this.page.event.key.Down);

【讨论】:

猜你喜欢
  • 2011-03-29
  • 1970-01-01
  • 2015-10-28
  • 2018-01-13
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多