我将 html 保存在变量中
var itinerary = $('.events_today').html() ;
我有很多 html 和一个要删除的按钮。它的 ID 为“myButton”。如何从保存在我的变量中的 html 中删除它
我建议这种方法
var itinerary = $('.events_today')
.clone(true) /* get a clone of the element and from it */
.find('#myButton') /* retrieve the button, then */
.remove() /* remove it, */
.end() /* return to the previous selection and */
.html() ; /* get the html */
尝试这个:
itinerary.filter(function() { return $(this).not("#myButton"); });
只需通过它的 id 定位元素并删除:
$('#myButton').remove()
然后获取您的行程:
var itinerary = $('.events_today').html() ;
// 以上将从 DOM 中删除按钮。要在不从 DOM 中取出按钮的情况下获取 html,您可以执行以下操作:
var itinerary = $('.events_today').clone(true).find('#myButton').remove().end().html();
在集合中找到元素并将其删除。
$('.events_today').find('#myButton').remove();
编辑:在意识到我可能误解了 OP 之后,这可能会起作用(虽然不是很漂亮)。
var html = $('.events_today').html();
// Parse the html, but don't add it to the DOM
var jqHtml = $(html);
// Find and remove the element with the specified id.
jqHtml.find('#myButton').remove();
// Get the new html without the myButton element.
var result = jqHtml.html();
更新:根据@Fabrizio Calderan 的回答,您可以使用jQuery 方法更好地完成我上面所做的事情。
尝试这个:
var html = $('#myHtml').clone(true).find('#elementThatYouWantToRemove').remove().end().html();