使用JavaScript或JQuery模拟用户点击

时间:2014-12-06 19:25:47

标签: javascript jquery html html5 jsp

我想要模拟用户点击的网站。在这个网站上,有以下div,我们称之为div1,其中有一个下拉菜单。实际上还有其他两个相似的div(让我们称之为div2和div3),但为了简单起见,我没有放在这里。当你在div1的下拉菜单中选择一个项目时,div2被启用(默认情况下在开始时被禁用),并且它的菜单内容是根据从div1中选择的项目从数据库中获取的。

我可以使用以下脚本选择菜单项。

代码:

function setSelectedValue(selectObj, valueToSet) { 
    for (var i = 0; i < selectObj.options.length; i++) { 
        if (selectObj.options[i].value== valueToSet) {
            selectObj.options[i].selected = true;
            return;
       }
      }
     }

var number = document.getElementById('level1-option');
setSelectedValue(number,  "p3");

然而,当我这样做时,div2永远不会启用。我尝试了jQuery代码在下拉菜单上发出更改信号,但它不起作用。当我调试下面的html代码时,我在那里看到了按钮标签,我立即认为它在有点击时提交。但是,我没有看到任何形式。如果我使用chrome调试网站,我看到当我在菜单中选择一个项目时,代码会跳转不同的js文件。任何人都可以指导我如何在选择项目时找出触发的信号?显然,他们在网站上做了一些技巧,以防止正常的点击方式

代码:

<div data-custom-select="" class="custom-select focus">
  <label for="level1-option" class="has-hidden-label label-text">Sections</label>
  <span class="btn-select icon-down_thin">Choose a section</span>
  <select class="categories-options" data-level="1" name="level1-option" id="level1-option" required="">
    <option value="">Choose a section</option>
    <option value="p1" data-href="/callback/discovery/p1/">P1</option>
    <option value="p2" data-href="/callback/discovery/p2/">P2</option>
    <option value="p3" data-href="/callback/discovery/p3/">P3</option>
    <option value="p4" data-href="/callback/discovery/p4/">P4</option>
  </select>
<span class="icon-down_thin"></span>
<button type="submit" class="category-submit ui-button-secondary ">Choose</button>

4 个答案:

答案 0 :(得分:1)

尝试......

$(元素)触发( '点击');

...来自jQuery。

答案 1 :(得分:1)

通常你可以使用:

$("#level1-option").val(valueToSet).trigger("click")

$("#level1-option").val(valueToSet).trigger("change")

但它可能取决于网页上的其余代码。

答案 2 :(得分:1)

尝试在更改其值后调度onchange事件:

var number = document.getElementById('level1-option');
setSelectedValue(number,  "p3");
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
number.dispatchEvent(evt);

答案 3 :(得分:1)

抱歉,我无法解决叠加问题。你的标记非常复杂。

无论如何,我为数据库中的更新/获取数据编了一些代码。请在下面找到它的演示。 该演示也在jsFiddle

JSON数据如下所示{"data": ["1st_1", "1st_2", "1st_3"]}

在我的工作中,我有一个问题不容易解决,但另一个SO question在这里有所帮助。如果您只使用change事件,则无法触发第一个元素来获取下一个数据。 反击技巧很有效。

var dynamicOptions = (function () {

    var url; // here you can add your url to the backend script
    // urlList only required for demo because no backend available
    var urlList = ['http://www.mocky.io/v2/54839e2a2f4b84a0041bba49',
        'http://www.mocky.io/v2/54839e4c2f4b84a5041bba4a',
        'http://www.mocky.io/v2/54839e6a2f4b84a9041bba4b'];
    
    var cc = 0; // click counter

    // e.g. $optionEl = $('#firstSelection');
    // $nextOptionEl = $('#secondSelection');
    function Selector($optionEl, $nextOptionEl) {
        this.$optionEl = $optionEl;
        this.$nextOptionEl = $nextOptionEl;
       
        this.ajaxRequest = function (optionValue) {
            return $.ajax({
                type: 'GET', // later 'POST'
                //data: {'data': optionValue}, // for posting
                url: url,
                contentType: "application/json",
                dataType: 'jsonp',
                context: this,
            });
        };
      
        this.getData = function(value) {
            url = urlList[value]; // simulating backend returns based on this value
            var ajaxReq = this.ajaxRequest(value); // this.value not used in this demo
            ajaxReq.success(this.jsonCallback)
                .fail(function (xhr) {
                alert("error" + xhr.responseText);
            });
        };
        // handle click and change event. Source from here: https://stackoverflow.com/questions/11002421/jquery-event-to-fire-when-a-drop-down-is-selected-but-the-value-is-not-change
        this.clickHandler = function ($element) {
            //console.log($element);
            var that = this;
            return $element.click(function () {
                //console.log('clicked');
                cc++;
                if (cc == 2) {
                    $(this).change();
                    cc = 0;
                }
            }).change(function (e) {
                cc = -1; // change triggered
                //console.log(this.value);
                that.getData(this.value);
            });
        }

        this.clickHandler($optionEl);

        this.jsonCallback = function (json) {
            var $nextEl = this.$nextOptionEl;
            $nextEl.empty();                    // clear selection
            $nextEl.prop('disabled', false);    // enable 2nd select
           
            this.triggerChangeEvent(); // maybe a check if they really changed would be good
            $.each(json.data, function (index, value) {
                $('<option/>')
                    .val(index)
                    .text(value)
                    .appendTo($nextEl);
            });
        };

        this.triggerChangeEvent = function () {
            var event = jQuery.Event("optionsChanged");
            event.context = this;
            event.message = "Options changed, update other depending options";
            event.time = new Date();

            $.event.trigger(event);
        };
    }

    return {
        Selector: Selector
    }; // make Selector public
})();

$(function () {
    var $first = $('#firstSelection');
    var $second = $('#secondSelection');
    var $third = $('#thirdSelection');

    // use our dynamic options selector class
    var options12 = new dynamicOptions.Selector($first, $second);
    var options23 = new dynamicOptions.Selector($second, $third);

    $(document).on('optionsChanged', function (e) {
        console.log("options changed", e);
        var obj_id = e.context.id;
        //console.log(obj_id);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div>
    <form role="form">
        <div class="form-group">
            <label>Please select first value:</label>
            <select id="firstSelection" class="form-control">
                <option value="0">0</option>
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
        </div>
        <div class="form-group">
            <label>Please select second value:</label>
            <select id="secondSelection" class="form-control" disabled="true">
                <!-- fetched from server -->
            </select>
        </div>
        <div class="form-group">
            <label>Please select third value:</label>
            <select id="thirdSelection" class="form-control" disabled="true">
                <!-- fetched from server -->
            </select>
        </div>
    </form>
</div>