字符串到jQuery对象,如何删除元素 [英] String to jQuery object, how to remove elements

查看:59
本文介绍了字符串到jQuery对象,如何删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试操作textarea中的一些html(不是页面的一部分),但我希望能够在其上执行jQuery函数。

I'm trying to manipulate some html which is in a textarea (not part of the page) but I want to be able to perform jQuery functions on it.

这里我试图用1234的attr'my_id'删除div,但结果数据保持不变?

Here I am trying to remove the div with the attr 'my_id' of 1234, but the resulting data remains the same?

var data = "<div>something<div my_id='1224'>blah</div><div my_id='1234'>xx123</div></div>";

var id = '1234';

$(data).remove('[my_id="'+id+'"]');

alert($(data).html());

显然只是使用警报进行调试。

Obviously just using alert for debugging.

推荐答案

var data = "<div>something<div my_id='1224'>blah</div><div my_id='1234'>xx123</div></div>";

var id = '1234';

var $data = $(data);  // create elements from the string, and cache them

$data.find('[my_id="'+id+'"]').remove(); // find and remove the nested element

alert($data.html());  // alert the resulting HTML




  1. 你给了 .remove()一个选择器,仅适用于顶级元素。目标元素是嵌套的。

  1. You were giving .remove() a selector, which only works on top level elements. The targeted element is nested.

当你执行 alert($(data).html()); ,您使用的是原始字符串,该字符串未被修改。你需要创建元素,引用jQuery对象,进行操作,然后使用相同的jQuery对象来查看结果。

When you did alert($(data).html());, you were using the original string, which isn't modified. You need to create the elements, reference the jQuery object, do your manipulation, then use that same jQuery object to see the result.

这篇关于字符串到jQuery对象,如何删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆