[英]JQuery find and update attribute of child element then return the parent element
I have a string representing a checkbox such as follows:我有一个表示复选框的字符串,如下所示:
var checkbox = "<div class="text-center"><label for="cb_1"><input type="checkbox" id="cb_1"/></label></div>";
I want to make the checkbox checked (add the attribute checked="checked") such that the string becomes:我想选中复选框(添加属性 checked="checked"),使字符串变为:
<div class="text-center"><label for="cb_1"><input type="checkbox" id="cb_1" checked="checked"/></label></div>;
I have tried the following:我尝试了以下方法:
$(checkbox).find('input').attr('checked', true).end().html();
This return the following:这将返回以下内容:
<label for="cb_1"><input type="checkbox" id="cb_1" checked="checked"/></label>
My question is why is the first div not returned and how can I return the whole thing like:我的问题是为什么没有返回第一个 div 以及如何返回整个内容,例如:
<div class="text-center"><label for="cb_1"><input type="checkbox" id="cb_1" checked="checked"/></label></div>;
html()
in jquery uses innerHTML
property. jquery 中的
html()
使用innerHTML
属性。 In this case, outerHTML
need to be used, So在这种情况下,需要使用
outerHTML
,所以
Try using prop('outerHTML')
尝试使用
prop('outerHTML')
var checkbox = '<div class="text-center"><label for="cb_1"><input type="checkbox" id="cb_1"/></label></div>'; console.log($(checkbox).find('input').attr('checked', true).end().prop('outerHTML'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Reference参考
https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML
尝试这个
$($(checkbox).find('input').attr('checked', true).end().parentNode).html();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.