jQuery:选择调用该函数的元素 [英] Jquery: Select the element that called the function

查看:145
本文介绍了jQuery:选择调用该函数的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过onclick属性在元素本身中调用函数,因为我需要php动态地在函数的参数之一中提供一个值.当我尝试通过$(this)引用函数中的调用元素时,它将最终引用整个窗口而不是整个元素.我该如何解决?

I'm calling a function in the element itself via an onclick attribute because I need php to dynamically give a value in one of the function's parameters. When I try to reference the calling element in the function via $(this), it ends up referencing the entire window and not the element. How do I fix this?

推荐答案

我怀疑您确实需要使用内联onclick属性.您可以通过多种不同方式将数据存储在元素中.在不知道您需要传递的参数是什么的情况下,很难确切地说出如何做,但是我会举一些例子.

I doubt you genuinely do need to use an inline onclick attribute. You can store data in an element in a variety of different ways. It's hard to say exactly how you would do it without knowing what the parameter you need to pass is, but I'll give some examples.

最灵活的可能是data-属性:

<a href="#" id="subject" data-type="fiction">Text</a>

然后您可以通过以下方式访问信息:

You could then access the information in the following way:

$(document).ready(function(){
    $('#subject').click(function(){
        $type = $(this).data('type'); // this works as of jQuery 1.4.3, otherwise $(this).attr('data-type');

        // do your handling here, using $type
    });
});

您还可以使用类,创建全局变量的脚本标签以及各种方法来执行此操作.这些几乎肯定比将jQuery处理程序放入onclick属性更好.

You could also do this using classes, script tags that create global variables, all kinds of methods. These will almost certainly be better than putting jQuery handlers in onclick attributes.

这篇关于jQuery:选择调用该函数的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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