简体   繁体   English

在td jquery中添加div

[英]add a div inside a td jquery

I want to add a div inside a td. 我想在TD内添加div。

My td before 我的td之前

<td>Fiction</td>

After i write code 我写代码后

var cell =  getCell(indexRow + 1, colIndex);
var wrap = $('<div/>').attr('id', 'container');

cell.append(wrap);

Now it becomes 现在变成

<td> Fiction [object Object] </td>

javascript javascript

function getCell(row, col){

    var currentRow = $('#MapDetails tr')[row];
    var cell = $(currentRow).find('td')[col];

    return cell;
}

There was a couple syntax errors. 有几个语法错误。

Look this code and feel free to ask questions... 查看此代码,随时提问...

 function getCell(row, col){ var currentRow = $('#MapDetails tr'); var cell = currentRow.eq(row).find('td').eq(col); return cell; } var indexRow = 0; var colIndex = 0; var cell = getCell(indexRow + 1, colIndex); var wrap = $('<div>').attr('id', 'container').text("I'm the new div!"); cell.append(wrap); 
 td{ border:1px solid black; } td div{ border: 2px solid red; padding: 4px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="MapDetails"> <tr> <th>Header</th> </tr> <tr> <td>Fiction</td> </tr> </table> 

.attr(key, value) only sets the attributes to the jQuery object. .attr(key, value)仅将属性设置为jQuery对象。

You might want to create one with the specific attributes by following code. 您可能想通过以下代码创建一个具有特定属性的对象。

var cell =  getCell(indexRow + 1, colIndex);
var wrap = $('<div />', {id: 'container'});

cell.append(wrap);

Or If you want wrap to be the only element inside <td> then 或者,如果您希望wrap<td>的唯一元素,则

cell.html(wrap);

使用hmlt而不是append希望这可以使用像cell.html(“”)这样的html来解决,让我知道这是否行不通,

<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
      $(function() {
        var indexRow = 0;
        var colIndex = 0;
        var cell = getCell(indexRow + 1, colIndex),
          $cell = $(cell);
        var wrap = $('<div/>').attr('id', 'container').text($cell.text());

        $cell.html(wrap);

        function getCell(row, col) {
          var currentRow = $('#MapDetails tr')[row];
          var cell = $(currentRow).find('td')[col];

          return cell;
        }
      });

    </script>
  </head>

  <body>
    <table id="MapDetails">
      <tr>
        <th>name</th>
        <th>title</th>
      </tr>
      <tr>
        <td>Samra</td>
        <td>Developer</td>
      </tr>
      <tr>
        <td>Debasis</td>
        <td>Developer</td>
      </tr>
    </table>
  </body>

</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM