触发DOM元素上的点击事件

Trigger click event on DOM element

本文关键字:事件 DOM 元素 触发      更新时间:2023-09-26

我尝试在选定的DOM元素上触发单击事件,但我的代码不起作用。

你可以看到我在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元素进行比较。

之后,我得到一个元素,我想触发一个点击事件。点击事件应该"执行"指定的函数。

谁能给我一个好的解决方案?

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

把click事件放在ready事件的顶部。点击事件需要在注册事件后触发

$(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();
    }
});

问题是您在将事件处理程序附加到它之前触发单击事件。所以你只需要在触发点击之前移动点击处理程序,一切都会像你预期的那样工作:

$(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