开发者

Take from a list only the element i just clicked and use it

i have a list and when someone clicks on an li element then with $.ajax() i fetch the specific data it wants.

for ie :

<li id="test1">test 1 </li>
<li id="test2">test 2 </li>
<li id="test3">test 3 </li>
...
<li id="testN">test N &l开发者_如何转开发t;/li>

So the ajax part is for test 1 :

$('#test1').click(function() {

 $.ajax({
  url: 'fetch.php',
  type: 'POST',
  data: { temp : 'test1'},
  success: function(data) {
    $('#test1').append(data);
  }    
});

and the same for 2,3,4...N

But the problem is it comes too much of code..ok its just copy paste but can i do it another way? meaning when i click test1 element jQuery finds out what element i clicked and runs for it...

Sorry my bad english thanks


Try:

<li class="test" id="test1">test 1 </li>
<li class="test" id="test2">test 2 </li>
<li class="test" id="test3">test 3 </li>
...
<li class="test" id="testN">test N </li>

and then

$('.test').click(function() {
    var $this = $(this);
    $.ajax({
         url: 'fetch.php',
         type: 'POST',
         data: { temp : $this.attr('id') },
         success: function(data) {
             $this.append(data);
        }    
    });
});


You could put a class="test" to all your LIs and select the class using $(".test") or assign a unique ID to the UL <ul id="tests"> and select only LIs in that UL $("#tests li")


Use the change even to only fire when you select an item from the list:

$('#test1').change(function() {
    $.ajax({
    url: 'fetch.php',
    type: 'POST',
    data: { temp : 'test1'},
    success: function(data) {
        $('#test1').append(data);
    }    
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜