簡體   English   中英

在DOM元素上觸發點擊事件

[英]Trigger click event on DOM element

我試圖在選定的DOM元素上觸發click事件,但是我的代碼無法正常工作。

您可以看到我對JSFiddle的嘗試。

<ul class="list-group">
    <a href="#" class="list-group-item" data-key="32">LG GOLA 8M</a>
    <a href="#" class="list-group-item" data-key="33">LG 5-6M</a>
    <a href="#" class="list-group-item" data-key="34">LP 5-6M</a>
</ul>

$(document).ready(function() {
    // I get the string tr from URL parameters
    var tr = "fix_LG%20GOLA%208M";
    if (tr !== null) {
        var terminrahmen = $('.list-group-item').filter(function() {
            return $(this).text() === decodeURI(tr).substring(4);
        });

        // Trigger click event on .list-group-item
        terminrahmen.click();
    }

    // The function to be executed
    $('.list-group-item').click(function() {
        alert($(this).text());
    });
});

加載DOM時,我從URL參數中收集了一些數據,並將數據與DOM元素進行了比較。 這部分工作正常。

之后,我得到一個元素,我想觸發一個click事件。 click事件應“執行”指定的功能。

有誰對我有一個好的解決方案? 提前致謝。

問題在於您在將事件處理程序附加到它之前觸發了click事件。 因此,您只需要在觸發點擊之前移動點擊處理程序,一切便會按預期工作:

$(document).ready(function() {
    // The function to be executed
    $('.list-group-item').click(function() {
        alert($(this).text());
    });
    // I get the string tr from URL parameters
    var tr = "fix_LG%20GOLA%208M";
    if (tr !== null) {
        var terminrahmen = $('.list-group-item').filter(function() {
            return $(this).text() === decodeURI(tr).substring(4);
        });

        // Trigger click event on .list-group-item
        terminrahmen.click();
    }

});

JSFiddle

http://jsfiddle.net/azg2R/2/

將click事件放在ready事件的頂部。.click事件需要在注冊事件后觸發。 以前沒有發生

$(document).ready(function() {           
    // The function to be executed
    $('.list-group-item').click(function() {
        alert($(this).text());
    });

    // I get the string tr from URL parameters
    var tr = "fix_LG%20GOLA%208M";
    if (tr !== null) {
        var terminrahmen = $('.list-group-item').filter(function() {
            return $(this).text() === decodeURI(tr).substring(4);
        });

        // Trigger click event on .list-group-item
        terminrahmen.click();
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM