开发者

jQuery getJSON: getting clicked 'this' from several levels down

开发者 https://www.devze.com 2023-03-31 15:05 出处:网络
Summary: Trying to reference clicked \"this\" from several calls deep. Hi All, I have a situation where I have a set of buttons (Button 1 - 6) in the form of an unordered list.When one of the butt

Summary: Trying to reference clicked "this" from several calls deep.

Hi All,

I have a situation where I have a set of buttons (Button 1 - 6) in the form of an unordered list. When one of the buttons is clicked, I'd like it to getJSON load some more <li> options (based on the json data) underneath the button that was clicked. Right now, when I click one of the buttons, it loads the JSON-based options under all of the buttons. The problem is that I'm not sure how to reference the "this" of the "click" function call rather than the "this" associated with one of the nested calls.

I'm a biginner when it comes to jQuery, so I relize that this is probably an easy fix. Forgive me if my terminology is off a bit.

Thank you for reading and for considering my question.

Here is the associated javascript:

$(".block-buttons .level1 a.level1_a").click(function () 
{
  $.getJSON('api/1/test.json', 
    function(data) {    
        ul = $('<ul>');
        $.each(data.items,
        function( intIndex, objValue )
        {
            a = $("&l开发者_开发百科t;a/>").text(objValue.name);
            li = $('<li>').attr("class",'level2').append(a);
            ul.append(li);
        });
        /* Here is where the problem lies.  I'd like to append the 
           new JSON-loaded data to the ".level1" element that was clicked
           and not to all of the ".level1" elements.  I need to figure out how 
           to replace the ".level1" below with some reference to the "this"
           from the clicked element.  
        */
        $(".level1").append(ul);            
      });   
  }
  return false; 
});

Here is the associated HTML:

<div class="block-center block-buttons">
<ul>
<li class="top"><a class="top_a" href="">Make a Selection</a>
    <ul>
    <li class="level1"><a class="level1_a" id="button_1" href="">Button 1</a></li>
    <li class="level1"><a class="level1_a" id="button_2" href="">Button 2</a></li>
    <li class="level1"><a class="level1_a" id="button_3" href="">Button 3</a></li>
    <li class="level1"><a class="level1_a" id="button_4" href="">Button 4</a></li>
    <li class="level1"><a class="level1_a" id="button_5" href="">Button 5</a></li>
    <li class="level1"><a class="level1_a" id="button_6" href="">Button 6</a></li>
    </ul>
</li>
</ul>
</div>


Assign the list item to a variable, eg

$(".block-buttons .level1 a.level1_a").click(function () 
{
    var listItem = $(this).parent('li');
    $.getJSON('api/1/test.json', //etc


easiest way is to do

var that = this;

at the level you want to preserve this - and then access it as that later.

0

精彩评论

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