2010-04-20 46 views
0

我想使用動態jQuery腳本提交一次,但它不起作用 我的代碼有什麼問題?jquery動態結構與Eq

$(document).ready(function(){ 

    $("#foo").each(function(i) 
    { 

     $("button#foo").eq(i).click(function() 
      { 
       var a = this.val(); 
       alert(a); 
      }); 
    }); 

}); 

<div id="tabs-1"><input type="type" value="one"><button id="foo"></button></div> 

<div id="tabs-2"><input type="type" value="two"><button id="foo"></button></div> 

<div id="tabs-3"><input type="type" value="tree"><button id="foo"></button></div> 

感謝mapet

+1

ID應該在所有的元素獨特 – 2010-04-20 09:20:20

回答

2

嘗試

var a = this.value; 

值是一個屬性,而不是一個方法

在jQuery中您可以使用

$(this).val() 

你的整個代碼應該是這樣的

$(document).ready(function(){ 
    $("#foo").click(function(){ 
     var a = this.value; // or you can use $(this).val() 
     alert(a); 
    }); 
}); 

編輯

給所有的按鈕,一個類名和使用類選擇分配click事件。改變你的按鈕ID。 ID在文檔中應該是唯一的。

$("button.btnclass").click(function(){ 
    // to get the value of the input previous to the current button element 
    var val = $(this).prev().val(); 
    alert (val); 
}); 

Working Demo

第二個編輯

$(function(){ 
    $("button.btnclass").click(function(){ 
    var currentElem = $(this); 
    var val = currentElem.prev().val(); 
    var id = currentElem.attr("id"); 

    switch(id) 
    { 
     case "foo1" : alert("ajax1"); 
        break; 
     case "foo2" : alert("ajax2"); 
        break; 
     case "foo3" : alert("ajax3"); 
        break; 
    } 
    }); 
});​ 
+0

但rahul我如何確定點擊button.1或2?如果(點擊按鈕1) ajax get; } else { ajax get 2; } – mapet 2010-04-20 09:40:00

+0

編輯我的回答 – rahul 2010-04-20 10:08:53

+0

你得它.. rahul非常感謝^^ – mapet 2010-04-20 10:41:29

1

問題是你重複的ID。 ID必須是唯一的。另外你在做什麼也沒有什麼意義。你想達到什麼目的?

+0

我有標籤與不同的內容我希望它動態的,所以我代碼將不會多餘.. 像..(功能() { \t content ... 1 }); (功能() { \t內容... 2 }); (「#foo3」)。click(function() { \t content ... 2 }); – mapet 2010-04-20 09:27:30