2015-10-29 19 views
0

我有一個HTML表,隨後以簡單的形式,它接受象下面選擇行和使用jquery和更新其內容

<table border="1" style="width:100%"> 
    <tr> 
    <td>Row 1 Col1</td> 
    <td>Row 1 Col2</td> 
    <td>Row 1 Col3</td> 
    <td>Row 1 Col4</td> 
    <td>Row 1 Col5</td> 
    <td>Row 1 Col6</td> 
    </tr> 
    <tr> 
    <td>Row 2 Col1</td> 
    <td>Row 2 Col2</td> 
    <td>Row 2 Col3</td> 
    <td>Row 2 Col4</td> 
    <td>Row 2 Col5</td> 
    <td>Row 2 Col6</td> 
    </tr> 
    <tr> 
    <td>Row 3 Col1</td> 
    <td>Row 3 Col2</td> 
    <td>Row 3 Col3</td> 
    <td>Row 3 Col4</td> 
    <td>Row 3 Col5</td> 
    <td>Row 3 Col6</td> 
    </tr> 
</table> 
<form> 
     <input type="text" placeholder="Row" value="row"/> 
     <input type="text" placeholder="Column" value="column"/> 
     <button id="submitButton" type="submit"> Submit </button> 
</form> 

表的行和列可以改變,並且可以將表的行和列的表中的colums有n個行和列。我想要做的是基於用戶輸入(選擇行和列並提交)我想更新用戶選擇的行和列的內容來說「你好」。如果用戶選擇一列,則不可用的行組合會提示錯誤消息。我怎麼能在jQuery中做到這一點。

在此先感謝。

回答

1
$('#submitButton').click(
function(){ 
    var numrow = $('#numrow').val(); 
    var numcol = $('#numcol').val(); 
    var enttotal = numrow * numcol; 
    var lenrow = $('.dataupdate tr').length; 
    var lencol = $('.dataupdate tr:first-child td').length; 
    var tcol = $('.dataupdate tr td').length; 
if(numrow <= lenrow && numcol <= lencol && enttotal <= tcol){ 
    $('.dataupdate tr:nth-child('+numrow+') td:nth-child('+numcol+')').html('Hello') 
    } 
    else { alert('there is no such column in this table'); } 
    }); 

這是工作提琴鏈接 http://jsfiddle.net/6vj92vcp/

1

您可以使用這樣的,

$("#submitButton").click(function (e) { 
    e.preventDefault(); 
    var r = parseInt($("#row").val()) - 1; 
    var c = parseInt($("#column").val()) - 1; 
    $("table").find("tr").eq(r).find("td").eq(c).text("hello"); 

}); 

Fiddle

這是一個UNDEX爲基礎的方法。首先,您需要使用.eq()選擇器找到第n行。由於索引從0開始,因此需要將實際值減1。

您可以使用.find()方法獲取所有子元素。

1
$(document).ready(function(){ 

    $("#submitButton").click(function(){  
     var row  = parseInt($("#rows").val())-1; 
     var col  = parseInt($("#cows").val())-1; 
     var greeting = "hello"; 

     if(isNaN(row)|| isNaN(col)) { 
      alert('Please enter a valid row and column number'); 
      return false; 
     } 

     var x = $("table").find("tr").eq(row).find("td").eq(col); 
     if(x.length==0) 
      alert('Such a row and column not found '); 
     else if(x.text()==greeting) 
      alert("Already selected "); 
     else 
      x.text(greeting); 
     return false; 
    }); 
}); 

http://jsfiddle.net/tintucraju/fm0sL4s9/