2015-04-12 48 views
1

我目前正在試圖添加一個jQuery函數到一排單選按鈕。問題是我需要動態添加多行。現在,在這個例子中,我只在newNodes數組中添加了2個元素,但在我的應用程序中,newNodes可能有許多不同的大小。添加JQuery功能來動態創建單選按鈕

所以基本上我想添加的查詢功能是這樣的:

$('#rowID input').on('change', function() { 
    alert($('input[name=i]:checked', '#rowID').val()); 
}); 

如果它存在的for循環中,並添加每個新行。 「rowID」是分配給唯一行標識符的變量,然後使用循環迭代器「i」來區分每行的單選按鈕。

下面是HTML:

<form id="createEdges" method="POST> 
    <fieldset> 
     <legend class="title">Modify the graph!</legend> 
     <table id="createEdgesTable"> 
     </table>  
     <input type="button" class="btn btn-default" id="backToThirdForm" onclick="goBackToForm3()" value="Back"/> 
    </fieldset> 

這裏是JavaScript:

newNodes = []; 
newNodes.push(0); 
newNodes.push(1); 

//get HTML Table to add rows in 
var edgeTable = document.getElementById("createEdgesTable"); 
//Create a table row for each node 
    for (var i in newNodes) { 
     var row = edgeTable.insertRow(); 
     row.id = "node" + i; 

     //Show name of the node 
     var td = document.createElement('td'); 
     var text = document.createTextNode(newNodes[i]); 
     td.appendChild(text); 
     row.appendChild(td); 

     //Choice for showing node 
     var td2 = document.createElement('td'); 
     var radioButton1 = document.createElement('input'); 
     radioButton1.type = "radio"; 
     radioButton1.name = i; 
     radioButton1.value = "showNode"; 
     td2.appendChild(radioButton1); 
     row.appendChild(td2); 

     //Choice for creating edge 
     var td3 = document.createElement('td'); 
     var radioButton2 = document.createElement('input'); 
     radioButton2.type = "radio"; 
     radioButton2.name = i; 
     radioButton2.value = "createEdge"; 
     td3.appendChild(radioButton2); 
     row.appendChild(td3); 

     //Choice for deleting node 
     var td4 = document.createElement('td'); 
     var radioButton3 = document.createElement('input'); 
     radioButton3.type = "radio"; 
     radioButton3.name = i; 
     radioButton3.value = "removeNode"; 
     td4.appendChild(radioButton3); 
     row.appendChild(td4); 

     var rowID = row.id; 


    } 

$('#node0 input').on('change', function() { 
    alert($('input[name=0]:checked', '#node0').val()); 
}); 

的jsfiddle:https://jsfiddle.net/nxexrq9y/

如何使這項工作的每一行任何的例子嗎?我對JQuery相對來說比較陌生,現在已經陷入這個問題很長一段時間了。感謝您的時間和幫助!

回答

4

只需使用以下代碼更改您的腳本。

$('tr[id^=node] input').on('change', function() { 
    alert(this.value); 
}); 

說明: 腳本找到node任何trid開始。這涵蓋了所有動態生成的TR。進一步的選擇在每個TR中縮減爲只有input元素,並且註冊該元素的改變事件。在那個變化事件中,你已經獲得了這個元素,所以你可以很容易地訪問它的價值。

這裏是Js Fiddle Link

另外,如果你想知道點擊無線電落在哪個節點,你可以檢查出this js fiddle

$('tr[id^=node] input').on('change', function() { 
    var row = $(this).parents('tr:first').get(0); 
    alert('Node: '+ row.id+ ' value:' + this.value); 
}); 
+0

謝謝!這工作完美。 – user3547551