【问题标题】:How to use onhashchange with dynamic items如何将 onhashchange 与动态项目一起使用
【发布时间】:2013-10-21 20:15:13
【问题描述】:

所以,我在网页上有两个选择框,但在不同的锚点中(一个在页面上,另一个在 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 时,我是一个完整的菜鸟。提前致谢

【问题讨论】:

  • "它在哪个锚点" = 嗯?
  • 请告诉我你的代码真的不是这样缩进的 :-)
  • @cbuckley 不,它更干净,就像这里的格式一样

标签: javascript jquery html url hashchange


【解决方案1】:

除了你的函数看起来像什么外,它现在还没有在哈希更改时执行。

你使用 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 不是来自您的域,您将无法从中获取任何数据。如果是这种情况,请阅读有关same origin policy 的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-14
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多