jQuery获取< a>的哈希使用.on()事件的元素 [英] jQuery get hash of <a> element using .on() event

查看:106
本文介绍了jQuery获取< a>的哈希使用.on()事件的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我被引爆手册参考之前,我已经研究了很长一段时间,并且一直死胡同.甚至不确定如何正确调试它.因此,如果引用了任何参考文献,请确保对它们进行了很好的注释和指导.这是由于我是一名PHP/mySQL开发人员,而JavaScript对象参考模型对我来说有些困惑(但绝对是我会努力学习的!:)).

Before I get flamed with references to manuals, I have been researching this for quite some time, and keep getting dead ends. Not even sure how to debug it properly. So if any references are cited, please ensure they are well-commented and instructional. This due to me being a PHP/mySQL developer, and the JavaScript object reference model is a bit confusing to me (but definitely doing my best to learn! :) ).

我正在尝试使用jQuery v1.7.2更新我对jQuery的了解.显然,直播事件已被弃用,并已由.on()代替. jQuery文档说不要使用.on()将旧的单击"或实时"事件与任何脚本混合.

I am trying to update my knowledge of jQuery using jQuery v1.7.2. Apparently the live event has been deprecated, and has been replaced by .on(). The jQuery docs say not to blend old 'click' or 'live' events with any scripts using .on().

在尝试习惯on的同时,我试图捕获给定URL的哈希值.

While trying to get used to using on, I am trying to capture the hash of a given url.

页面如下(标题已加载jquery.min.1.7.2.js):

The page is as follows (header has already loaded jquery.min.1.7.2.js):

    <div id='menuHolder' style="position:relative; margin-left:50px;margin-bottom:30px; padding-top:35px; min-width:600px;z-index:998;">
      <ul id="menu">
         <li><a href="#">Events</a>
            <ul id="events">
                <li>
                    <img class="corner_inset_left" alt="" src="images/menu/corner_inset_left.png"/>
                    <a id="linker21 menu" class="test AJAXcaller" href="index.php#?p=1&amp;d=AJAXcontent&i=1&amp;k=<?=$_SESSION['authcpanel']['key']?>" rel="nofollow">Upcoming Events</a>
                    <img class="corner_inset_right" alt="" src="images/menu/corner_inset_right.png"/>
                </li>
                <li><a href="#">List All Events</a></li>
                <li><a id="linkermenu" class="test AJAXcaller" href="index.php#?p=24&amp;d=AJAXcontent&i=1&amp;k=<?=$_SESSION['authcpanel']['key']?>" rel="nofollow">Add Events</a></li>
                <li class="last">
                    <img class="corner_left" alt="" src="images/menu/corner_left.png"/>
                    <img class="middle" alt="" src="images/menu/dot.gif"/>
                    <img class="corner_right" alt="" src="images/menu/corner_right.png"/>
                </li>
            </ul>
         </li>
      </ul>
    </div>

<script>
    $(document).on("click", "a.AJAXcaller", function(){ 
        alert("Goodbye!");
        alert($(this).attr("hash"));
    }); 
</script>

第一个警报在单击添加事件"链接(带有哈希)时触发,中继再见!",然后第二个处理程序触发并中继未定义".我将如何访问此哈希?

The first alert fires on clicking the 'Add Events' link (which has a hash), relays 'Goodbye!', then the second handler fires and relays 'undefined'. How would I access this hash?

我的旧代码如下,并且可以正常工作,但是任何称为页面的ajax都不会附加事件处理程序,这就是为什么我使用.on()事件的原因.另外,如果这次我要学习正确的方法;),我不希望使用不推荐使用的功能...

My old code is as follows, and it works, but any ajax called pages won't have event handlers attached, which is why I'm using the .on() event. Also, If I'm going to learn how to do it PROPERLY this time ;), I don't want deprecated functions involved...

旧代码(有效)

OLD CODE(works)

var linkClickAction = {
        'a.AJAXcaller' : function(element){
            element.onclick = function(){
                var locationString = $(this).attr("hash");
                locationString = locationString.replace(/.*\#(.*)/, "$1")
            var parameterString = locationString.replace(/.*\?(.*)/, "$1"); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5');

            var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5');
            var parameterList = new Array();
            for (j = 0; j < parameterTokens.length; j++) {
                var parameterName = parameterTokens[j].replace(/(.*)=.*/, "$1"); // j
                var parameterValue = parameterTokens[j].replace(/.*=(.*)/, "$1"); // 1
                parameterList[parameterName] = parameterValue;
            }
            var page = parameterList['p'];
            var key = parameterList['k'];
            var includesDir = parameterList['i'];
            var changeDiv = parameterList['d'];

            sndReq(page,key,includesDir,changeDiv,parameterString); 
            return false;       
            }
        }

    };
Behaviour.register(linkClickAction);

还加载了一个behaviour.js脚本,该脚本基本上可以处理侦听器.那时我根本没有使用jQuery.相对来说,它很不错,而且是FAST(微小的.js文件,没有多余的代码),但在处理ui中的奇特事物时,我达到了能够编写有效JavaScript的极限.因此,无论如何,我必须在页面加载时加载jQuery脚本.看到它是如何加载的,我试图利用它的功能,而不是为页面加载添加更多不必要的脚本.因此,我想找到一个使用本机jQuery 1.7.2函数实现此目标的结果.

There was also a behaviour.js script loaded that basically handled the listener. I wasn't using jQuery at all at that time. It was nice, and FAST(tiny .js files, no extraneous code), comparatively speaking, but I hit my limit of being able to write effective JavaScript when it came to handling fancy things in my ui. So I have to load the jQuery script at page load anyways. Seeing as how it's already loaded, I'm trying to make use of it's functions instead of adding more unnecesarry scripts for my page to load. Thus I want to find a result that uses native jQuery 1.7.2 functions to accomplish this goal.

结果

RESULTS

事实证明,使用.attr()查找DOM对象的属性时,jQuery 1.6+可能会中断.因此,使用.prop()是方法.更正后的代码如下:

It turns out that jQuery 1.6+ can break when using the .attr() to find a property of a DOM object. So using .prop() was the way to go. Corrected code is as follows:

/*
Page:           rating.js
Created:        Aug 2006
Last Mod:       May 30, 2012
Modder:         Darren Maurer
*/

    function sndReq(page,key,includesDir,changeDiv,parameterString) {
        var divToChange = document.getElementById(changeDiv); // the Div that the data will be put into

        // switch Div with a loading div
        divToChange.innerHTML = '<div class="loading"><img src="images/loading.gif" title="Saskatoon.CityGuru.ca - Loading Page" alt="Saskatoon.CityGuru.ca - Loading Page" border="0"/></div>';

        if (includesDir == 1){
            //Find Current Working Directory.  Use to find path to call other files from
            /*var myloc = window.location.href;
            var locarray = myloc.split("/");
            delete locarray[(locarray.length-1)];
            var arraytext = locarray.join("/");
            */
            $.ajax({
                type: "POST",
                url: "AJAXCaller.php",
                data: parameterString,
                success: function(msg){
                    $('#'+changeDiv).html(msg);
                }
            });
        } 
    }

/* =======END AJAX FUNCTIONS================= */

/* =======BEGIN CLICK LISTENER FUNCTIONS================= */
/* Listens to any a href link that has a class containing ' AJAXcaller' */
/* ie. <a id="link1" class="test AJAXcaller" href="index.php#http://233.help?id=22&think=33" rel="nofollow">> AJAX TEST LINK <</a> */
$(document).on("click", "a.AJAXcaller", function(){
    alert($(this).prop("hash")); 
            var locationString = $(this).prop("hash");
            locationString = locationString.replace(/.*\#(.*)/, "$1")
            var parameterString = locationString.replace(/.*\?(.*)/, "$1"); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5');

            var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5');
            var parameterList = new Array();
            for (j = 0; j < parameterTokens.length; j++) {
                var parameterName = parameterTokens[j].replace(/(.*)=.*/, "$1"); // j
                var parameterValue = parameterTokens[j].replace(/.*=(.*)/, "$1"); // 1
                parameterList[parameterName] = parameterValue;
            }
            var page = parameterList['p'];
            var key = parameterList['k'];
            var includesDir = parameterList['i'];
            var changeDiv = parameterList['d'];
            sndReq(page,key,includesDir,changeDiv,parameterString); 
            return false;   
}); 

希望对某人有帮助,对我来说绝对是救生员!

hope that helps someone, it definitely was a lifesaver for me!

推荐答案

您的元素没有哈希属性.尝试获取href属性,并使用javascript的substr和indexOf函数在#

Your a element doesn't have a hash attribute. try getting the href attribute and using javascript's substr and indexOf functions to split the string at the #

var href = $(this).attr("href");
var hash = href.substr(href.indexOf("#"));

您也可以使用

$(this).prop("hash");

这篇关于jQuery获取&lt; a&gt;的哈希使用.on()事件的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆