如何使用CasperJS填充未嵌入表单的select元素? [英] How to fill a select element which is not embedded in a form with CasperJS?

查看:124
本文介绍了如何使用CasperJS填充未嵌入表单的select元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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我会使用

Usually with casperjs I would use

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

选择byc选项,但这次select元素未嵌入表单中!

to select option "byc" but this time the "select" element is not embedded in a form!

在这种情况下如何选择其值?

How can I choose its value in this case?

推荐答案

根据我的回答此处,您可以创建自己的功能,按值选择选项。这会更改可能不会触发select onChange事件的所选索引。

Adapted from my answer here, you can create your own function that selects an option by value. This changes the selected index which might not trigger the select onChange event.

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:

Alternative 1

Judging by the code of __utils__.fill() and casper.fillForm(), the selector of the form doesn't necessarily have to be a form. It may be a div:

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



替代2



如果仍然没有无法工作,您可能需要专注于页面上下文中的select元素,并使用PhantomJS发送上下键事件以更改值 page.sendEvent()

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

这篇关于如何使用CasperJS填充未嵌入表单的select元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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