开发者

Jquery: Select the element that called the function

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开发者_JAVA百科 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?


Try to send your element as a parameter to your function like that :

<input type="text" onclick="myfunction(this);"></input>

your function should be :

<script>
  function myfunction(currentElement){
    // ...
  }
</script>


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.

The most flexible would probably be in a data- attribute:

<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
    });
});

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.


The solution is to store the dynamic value in a custom attribute, not an onclick handler. The HTML spec defines any attribute starting with "data-" as custom data used exactly for things like this, and it's in the spec so it will validate. So you can do something like this (using PHP for the example, adjust accordingly):

<input type="text" id="some-input" data-some-dynamic="<?php echo $something; ?>">

Then retrieve in the javascript like so:

$(document).ready(function() {
  $('#some-input').click(function() {
    // $(this) -- is the input element
    // $(this).attr('some-dynamic-attribute') -- contains the dynamic data you need
  });
});

I think this method is superior to using attribute handlers like onclick="", simple because it is more solid from a design perspective; separation of concerns and all that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜