简体   繁体   English

从 JQuery 变量中删除所有标签元素

[英]Remove all label elements from JQuery variable

I use the following:我使用以下内容:

var transferTemplate = $('#transfersRow').html(); 

in order to store some html code in a variable, which results to:为了将一些 html 代码存储在一个变量中,结果是:

<div class="form-group row">

     <div class="col-lg-4">
         <label for="inc[1].a">Counterparty</label>
         <input type="text" class="form-control" id="inc[1].a" 
                name="inc[1].a" placeholder="Enter Counterparty">
     </div>

</div>

Now I would like to be able to remove all labels from the html code.现在我希望能够从 html 代码中删除所有标签。 I tried:我试过:

$(transferTemplate).find(label).remove();

$(transferTemplate).remove('label');

$(transferTemplate).filter('label').remove();

but none works.但没有一个工作。

First, you need to select the row that you want to remove labels at each row:首先,您需要在每一行中选择要删除标签的行:

Like this:像这样:

$(".row").each(function( index ) {
   $(this).find("label").remove(); //find label at each row and remove.
});

I hope that helps.我希望这有帮助。

I think that you are misunderstanding the result of html().我认为您误解了 html() 的结果。 It doesn't return a Jquery DOM object.它不返回 Jquery DOM 对象。 The result is just a string representation.结果只是一个字符串表示。 Just remove the .html() and I'm sure you will be able to call the functions you want.只需删除 .html() ,我相信您将能够调用您想要的函数。

var transferTemplate = $('#transfersRow');

This returns a string representation of the HTML:这将返回 HTML 的字符串表示形式:

var transferTemplate = $('#transfersRow').html(); 

You could remove the label from this string like this:您可以像这样从此字符串中删除标签:

$(transferTemplate).find('label').remove();

However, all that does it create a new jQuery object with the HTML minus the label.然而,这一切都会创建一个新的jQuery 对象,其中包含 HTML 减去标签。 It won't update the transferTemplate variable.它不会更新transferTemplate变量。

Instead, you could assign $(transferTemplate) to a new variable.相反,您可以将$(transferTemplate)分配给一个新变量。

That would allow you to remove the label and still have access to the updated HTML.这将允许您删除标签并仍然可以访问更新的 HTML。

Snippet片段

 var transferTemplate = $('#transfersRow').html(), template = $(transferTemplate); template.find('label').remove(); $('textarea').val(template.html());
 textarea { width: 100%; height: 10em; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="transfersRow"> <div class="form-group row"> <div class="col-lg-4"> <label for="inc[1].a">Counterparty</label> <input type="text" class="form-control" id="inc[1].a" name="inc[1].a" placeholder="Enter Counterparty"> </div> </div> </div> <hr> <strong>Output</strong> <textarea></textarea>

Well, I guess the correct way is: $(transferTemplate).find('label').remove();好吧,我想正确的方法是: $(transferTemplate).find('label').remove();

https://api.jquery.com/remove/ Like the penultimate example... https://api.jquery.com/remove/就像倒数第二个例子...

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

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