如何将 onhashchange 与动态项一起使用

How to use onhashchange with dynamic items

本文关键字:一起 动态 onhashchange      更新时间:2023-09-26

因此,我在网页上有两个选择框,但在不同的锚点中(一个在页面上,另一个在 iframe 中),我正在尝试获取代码以检测它位于哪个锚点中,然后将该框中的选定值中继到链接。这是我的代码:

function locationHashChanged() {
    if (location.hash === "#player") {
        function setText(text) {
            var selectVal = text;
            var url = $('twitter').attr("href");
            url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
            $('#twitter').attr("href", url);
        }
    }
    if (location.hash === "#embeds") {
        $(function () {
            var $twitter = $('twitter');
            $('#iframe').on('load', function () {
                $(this).contents().find('#cds').change(function () {
                    var selectVal = $(this).val() || 'nothing much';
                    url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
                     $('#twitter').attr("href", url);
                }).change();
            });
        });
    }
}

我知道这可能不对,或者接近正确,但我走在正确的轨道上吗?老实说,在javascript方面,我是一个彻头彻尾的菜鸟。提前致谢

除了你的函数到底是什么样子的,它现在没有在哈希更改时执行。

你使用 jQuery,所以你可以像这样侦听哈希变化:

$(window).on('hashchange', function() {
   // your locationHashChanged() function goes here
}); 

这样,每次哈希更改时,您的函数都将被执行。代码的基础是好的:

if (location.hash === "#player") {
    // this is executed if hash changed to #player
}
if (location.hash === "#embeds") {       
    // this is executed if hash changed to #embeds
}

虽然,在你的if块中,你声明函数(这在这里没有多大意义)。

另请注意,如果 iframe 不是来自您的网域,您将无法从中获取任何数据。如果是这种情况,请阅读有关同源政策的更多信息。