开发者

Invoking jQuery function without an element

开发者 https://www.devze.com 2022-12-31 14:40 出处:网络
So, I use jQuery quite extensively and I am well aware of the \"right\" way to do the below, but there are times where I want to solve it in a more generic way. I\'ll explain.

So, I use jQuery quite extensively and I am well aware of the "right" way to do the below, but there are times where I want to solve it in a more generic way. I'll explain.

So, I may have a link, like this: <a href='menu' class='popup'>Show menu</a>. Now, I have a jQuery function that fires on click for all a.popup that takes the href-attribute and shows the <div id='menu'></div> item (in this case). It also handles URL's if it can't find a DOM item with that ID.

No problem here. But, there are times when I don't have the same control over the coe where I can create a selectable target that way. Either because the code isn't created by me or because it is created through a chain of function that would all need a huge ovrhaul which I won't do.

So, from time to time, I would like to have this code:

<a href="javascript:popup('menu')">Show menu</a>

This would be in a case where I can only submit the label and the 开发者_开发百科HREF for a link. No class, no nothing.

Problem here is that the function popup() has no idea about what element invoked it, and in most cases that's not a problem for me, since I only need to know where the mouse cursor was upon invokation.

But in some cases, I use someone elses jQuery functions, like qTip or something else. so I still want to fire off qTip(); when clicking a link that runs this JS function, but what do I attach it to to make it show? I can't just runt $().qTip(); because that implies $(this) and "this" is undefined inside the function.

So how do I do it? Any ideas?


Is there anyway you change the javascript method to javascript:popup('menu', this);? I've used this method successfully many times.


Instead of referring to "this" try referring to $('a:focus') to refer to the link that was clicked.

Here's a quick and, as @Crescent Fresh would add, dirty (☺) sample:

<body>
<p><a href="javascript:popup('menu')">Show popup()</a></p>
<div id="menu" style="display:none">Today's menu</div>

<script type="text/javascript">
function popup(elm) {
    $('#' + elm).show();
    alert( $('a:focus').text() )
}
</script>
</body>

I tried just ":focus" but IE7 returned too much content. I tested this in FF 3.6.3, IE7, Chrome 4.1.249.1064 (all on Windows) and it seems OK, but I see now (when I was just about to hit "Post Your Answer") this relies on the browser's native support for querySelectorAll - see this jQuery Forum post ":focus selector filter?" and the jQuery.expr entry in the jQuery Source Viewer (where it appears Paul's idea was not implemented).


How about

<a href="javascript:popup(event, 'menu')">Show menu</a>

Once you get the event object you can virtually do anything to it.

0

精彩评论

暂无评论...
验证码 换一张
取 消