jquery - 如何让 jQuery 事件在指向 http ://www. website.com/#id 的直接链接上触发?

标签 jquery html events hyperlink

试图弄清楚如何让 jQuery 检测引用页面上唯一 ID 的超链接。我不仅希望在页面上单击元素时加载该事件,而且还希望在有人使用分配给该 #div 的唯一 #id 直接链接到该页面时加载该事件。

更新:

好的,这就是我到目前为止所拥有的,但它没有被触发。

    function opencontact() {
        $("#first-name-check").hide();
        $("#last-name-check").hide();
        $("#phone-number-check").hide();
        $("#email-address-check").hide();
        $("#customer-message-check").hide();
        $("#send").button("disable");
        $("#email-form").dialog("open");
    }

    $(".email").click(opencontact);

    var hash = window.location.hash.substring(1);
        alert(hash);
        if (hash == "contact") {
            opencontact();
        }

警报返回正确的#hash,所以我不知道出了什么问题。

对话框初始化如下:

   $(function() {
        $("#email-form").dialog({
            autoOpen: false,
            resizable: false,
            draggable: false,
            closeOnEscape: false,
            height: 600,
            width: 540,
            modal: true,
            buttons: {
                "Send Joe Your Message": {
                    text: "Send Joe Your Message",
                    id: "send",
                    click: function() {
                        $.post("email.php", $(this).find('input, textarea').serialize());
                        $(this).find('input, textarea').val("");
                        $(this).dialog("close");
                    },
                },
                Cancel: function() {
                    $(this).find('input, textarea').val("");
                    $(this).dialog("close");
                }
            }
        });

    });

最佳答案

像这样的事情应该可以解决问题:

//this will grab the url from the address bar
var oldUrl = document.location.href;
//now we need to find just the part after the #
var urlSlice = oldUrl.split('#',oldUrl.length);
//urlSlice is now an array of two items (one before the '#' one after)
//from which we can grab the div id
var divId = urlSlice[1];

//then if it is the id you want
if( divId === 'desiredID' ) {
    clickHandler();
}

function clickHandler() {
    //do stuff
}

就我个人而言,我会将所有这些都放在一个函数中以使其更简洁,但它也可以在函数之外工作。

关于jquery - 如何让 jQuery 事件在指向 http ://www. website.com/#id 的直接链接上触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16555859/

相关文章:

javascript - 使用javascript转义字符串中的特定字符

javascript - 使用带复选框的多选下拉列表搜索或过滤 jquery 数据表中的列

Javascript:如果没有 "document.body.onresize",更改 "console.log"不会生效

c# - ListPicker SelectionChanged 被多次调用

c++ - 是否可以在 Linux 中以编程方式单击另一个应用程序的按钮?

javascript - 将函数直接传递给 Change() 事件不起作用

javascript - 修复元素滚动到 Div

javascript - Jquery 附加超出最大高度

html - 如何使我的可滚动水平画廊以三张图片中的第一张为中心并使用 Bootstrap 进行响应?

javascript - html5 对矢量图形动画有用吗?