简体   繁体   English

jQuery没有追加整个生成的HTML(td标签)

[英]jQuery not appending the entire generated HTML (td tag)

I have this code: 我有这个代码:

var priceTextField = $("<td>").append(
  $("<input>")
  .addClass("form-control input-sm")
  .attr("type", "text")
  .attr("placeholder", "Input something or delete me!")
);

And when appending it by... 当附加...时

var priceDataRow = $("<tr>").append(
  priceTextField.clone().find("input").addClass("text-quantity")
).append(
  priceTextField.clone().find("input").addClass("text-price")
).append(
  $("<td>").append(
    $("<button>")
    .addClass("btn btn-danger btn-sm btn-block delete-btn")
    .attr("type", "button")
    .text("Delete")
  )
);

The <td> wrappers from the priceTextField clones are not appearing. priceTextField克隆的<td>包装器没有出现。 However, the button <td> wrappers are. 但是,按钮<td>包装器是。

Example Output: 示例输出:

<tr>
  <input class="form-control input-sm text-quantity" type="text" placeholder="Input something or delete me!" value="444">
  <input class="form-control input-sm text-price" type="text" placeholder="Input something or delete me!" value="44">
  <td>
    <button class="btn btn-danger btn-sm btn-block delete-btn" type="button">Delete</button>
  </td>
</tr>

Have I missed something obvious? 我错过了明显的东西吗? If someone could point me in the right direction that would be much appreciated. 如果有人能指出我正确的方向,将非常感激。

Cheers 干杯

When you did : priceTextField.clone().find("input").addClass("text-quantity") you actually took the input field and appended that. 当你这样做: priceTextField.clone().find("input").addClass("text-quantity")你实际上获取了输入字段并附加了它。 Not the <td> . 不是<td> Because you used find() 因为你使用了find()

https://api.jquery.com/find/ https://api.jquery.com/find/

Description : Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. 描述 :获取当前匹配元素集中每个元素的后代 ,由选择器,jQuery对象或元素过滤。

What you need is end() so that you can pick the <td> itself. 你需要的是end()以便你可以选择<td>本身。

https://api.jquery.com/end/ https://api.jquery.com/end/

Description: End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. 描述:结束当前链中最近的过滤操作,并将匹配元素集返回到先前的状态。

尝试使用.end()

priceTextField.clone().find("input").addClass("text-quantity").end()

You are only appending the input elements. 您只是附加输入元素。 This is how jQuery works: 这就是jQuery的工作原理:

This first example returns a clone of the "td" that you created before. 第一个示例返回您之前创建的“td”的克隆。

priceTextField.clone()

But when you do this the "input" element will be returned. 但是当你这样做时,将返回“input”元素。

priceTextField.clone().find("input")

What you need to do is save this in a variable first like this: 您需要做的是首先将其保存在变量中,如下所示:

var priceDataRow = $("<tr>");
var clonedTd = priceTextField.clone();
clonedTd.find("input").addClass("text-quantity");
$(priceDataRow).append(clonedTd);

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

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