2

I am trying to apply ajax call for the response received from json.

Below my HTML.

<div id = "tabs">
<ul>
<li><A href="#ed_pro">Product Category</A> </li>
<li><A href="#ed_img">Add Image</A> </li>
<li><A href="#ed_txt">Add Text</A></li>
</ul>    
<div id="ed_pro">
</div>
<div id="ed_img">
</div>
<div id="ed_txt">
</div>
</div>

and

function handleTabSelect(data) {
    var items = '<ul>';
    $.each(data, function(i, object) {
        items += '<li><a id="main_cat" href=#>' + object.img_cat_des + '</a></li>';
    });
    items += '</ul>';
    $('#ed_img').append(items);
    flag = 1;
}

$('#main_cat').click(function() {
    var url1 = $(this).attr("href");
    alert(url1);
});

$("#tabs").tabs();

$("#tabs").bind("tabsselect", function(e, tab) {

    if (flag == 0) {
        jQuery.ajax({
            type: 'POST',
            url: '?q=design/lab_tab',
            dataType: 'json',
            data: 'slider_value=' + tab.index,
            success: handleTabSelect,
            error: function(xhr, status) {
                alert(xhr.statusText);
            }

        });
    }
});​

After getting the response from json, the above script will append list of as

<ul>
<li>
<a id="main_cat" href="#">Animals</a>
</li>
<li>
<a id="main_cat" href="#">Astrology</a>
</li>
</ul>

How I can apply further ajax call for .

On clicking the a href, it never invokes

$('#main_cat').click(function () {
var url1 = $(this).attr("href");
alert (url1);
});

Thanks in advance.

4

2 回答 2

2
  <a id="main_cat" href="#">Animals</a>
  <a id="main_cat" href="#">Astrology</a>
  • Id should be unique, you have multiple elements with the same id => invalid HTML
  • use on to create a delegate event handler.

Fixed markup:

  <a class="main_cat" href="#">Animals</a>
  <a class="main_cat" href="#">Astrology</a>

Javascript:

$('staticContainer').on('click', '.main_cat', function(){
    var url1 = $(this).attr("href");
    alert (url1); 
});

You should replace selector: staticContainer to fetch the closest static(exist on DOM ready) element that contains the new anchors.

于 2012-04-21T18:06:26.677 回答
0

Thanks @gdoron, I got it.

$('#ed_img').bind('click', '.main_cat',function(event){ 
  var tg_element = $(event.target); 
  var url1 = tg_element.attr("href"); 
  alert (url1); 
}); 

Regards, Prabhu M K

于 2012-04-22T14:33:34.280 回答