简体   繁体   中英

add a div inside a td jquery

I want to add a div inside a td.

My td before

<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

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.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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