.click()的原始Javascript版本

时间:2014-11-17 18:43:01

标签: javascript jquery

我对jQuery的看法:

if ($('#vote_c').length > 0) {
    $('#vote_button').show().click();
}

我正在尝试重新编写它,因此它使用原始javascript:

if (document.getElementById('vote_c').length > 0) {
    // what goes here
}

3 个答案:

答案 0 :(得分:1)

document.getElementById('vote_button').onclick = function(){
    document.getElementById('vote_button').style.display = 'block';
};

哦,我的坏。我没有看到if语句,但它应该指向正确的方向。

答案 1 :(得分:1)

// cache lookup
var vote = document.getElementById('vote_c');
// using truthy/falsy value to determine existence
// proper test would be (vote !== null)
if (vote) {
    // this is probably closest to what .show() does
    // .show actually seems to track what the initial
    // computed display state for the element was and
    // along with .hide, toggles between the initial
    // state and 'none'.
    vote.style.display = '';
    // mimicking .click() is done any number of ways
    // but the easiest is below:
    vote.onclick(); // call any registered handlers for the click event;
    //
    // OR (second easiest way) you could define a click event:
    //
    var event = new MouseEvent('click', {
        "view": window,
        "bubbles": true,
        "cancelable": true
    });
    // and then "dispatch" that event to the targeted
    // element which should trigger the handlers
    vote.dispatchEvent(event);
}

答案 2 :(得分:0)

if (document.getElementById('vote_c')) {
    var btn = document.getElementById('vote_button');
    btn.style.display = "inline"; //show
    btn.click() //click
}