开发者

JQuery $this selector - how to make it work

I am having trouble with $this selector for JQuery. This is doing nothing. The fundamental core of the script is not failing though.

$(this).css("background-image", 
"url(http://www.divethegap.com/update/z-images/diving-trips/tabs/bases-z.png)");

Any ideas why it does not work? I have tried the same effect using class.

THE FULL CODE (as requested) http://jsfiddle.net/mcxez/1/:

Markup:

<a href="?accommodation" style="background-position:-15px top;" 
   onclick="inload('?accommodation'); return false">Accommodat开发者_如何学Cion</a>

<a href="?travel" style="background-position:-15px top;" 
   onclick="inload('?travel'); return false">Travel</a>

js:

function inload(thelink) {
    $('.TABbase').click(function(){
        $(this).css("background-image", 
            "url(http://www.divethegap.com/update/z-images/diving-trips/tabs/bases-z.png)"); 
    });

  return false;
}


in jQuery, this is normally a reference to something within a function.. like...

HTML

<button id="button1">1</button>
<button id="button2">2</button>

JS

$('button').click(function(){
    alert( $(this).attr('id') ); //either 'button1' or 'button2'
}

In this case, this refers to the button being clicked.

Perhaps you can share some more code as to what you are trying to accomplish.


Here is the revised HTML

<a href="?accommodation" style="background-position:-15px top;" data-href="?accomodation" class="my_class">Accommodation</a>
<a class="my_class" href="?travel" style="background-position:-15px top;" data-href="?travel" >Travel</a>

Here is the javascript

$(document).ready(function(){
  $(".my_class").click(function(){
    $(this).css("background-image", "url(http://www.divethegap.com/update/z-images/diving-trips/tabs/bases-z.png)");
    return false;
  });
});


Where are you calling this from? this is a special variable that refers to the object currently being referenced in a method that applies to it. If you're referencing this from outside of a method, it refers to the dom window. For example:

<script type='text/javascript'>
alert($(this)); // refers to window

$('body').bind('click', function() {
    alert($(this)); // refers to the jQuery object created by selecting the body element.
});
</script>


For $(this) to work (or this) it must be relevant to an element. For example :

<a href="#" onclick="alert($(this).html());return false">test</a>

or, inside a selector loop :

$('.someClass').each(function() {
   $(this).css('background-color','#333');
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜