2

删除 DOM 中的选项标签对我来说不是问题,但现在我必须删除变量中的选项标签。这就是我所拥有的:

var txt = "<select name='example'><option value='1'>Test</option></select>";
$(txt).find("select option[value='" + $(this).attr("id") + "']").remove();

选择器似乎是正确的,我已经用 text() 对其进行了调试,它给了我正确的值。但是变量 txt 没有改变 - 我做错了什么?

4

6 回答 6

2

You shouldn't use select in your selector. And you have to use $() to make it a jQuery object first. After that you can manipulate it.

var txt = "<select name='example'><option value='1'>Test</option></select>",
    $txt = $(txt);
$txt.find("option[value='" + $(this).attr("id") + "']").remove();
于 2012-08-02T09:54:49.950 回答
1

如果您期望 的值txt不会改变它 - jQuery 不会改变它(它不能;它是按值传递的,而不是引用传递),它只会从中创建一个伪 DOM 并删除该选项。不过,没有什么永久性的事情发生。

如果要检索受影响的结果,则需要将整个内容放在容器中并读回其 HTML:

var txt = "<p>this is a HTML <span>string</span></p>";
txt = $('<div />').append(txt).find('span').remove().end().html();

txt现在已span删除。

于 2012-08-02T09:53:54.503 回答
1

首先创建一个 jQuery 选择器,这样您就不必不断地将其重新转换为一个。

在您的查找中,您也不需要在选择select时再次指定.find()

为简单起见,我将结果缓存.find()到另一个选择器变量中,然后再将其删除。

下面的工作正常。好吧,如果我使用1而不是它工作正常,$(this).attr("id")因为我不知道你指的是什么$(this)

var $txt = $("<select name='example'><option value='1'>Test</option></select>");
//var $option = $txt.find("option[value='" + $(this).attr("id") + "']");
var $option = $txt.find("option[value='" + 1 + "']"); // selects option with value of 1
$option.remove(); // Removes option

工作演示

于 2012-08-02T09:54:35.037 回答
0

什么都没有,txt仍然只是一个String. 我猜你想要一个变量中的 DOM 片段,这将是:

var txt = "<select name='example'><option value='1'>Test</option></select>";
var $domSnippet=$(txt);
domSnippet.find("select option[value='" + $(this).attr("id") + "']").remove();
于 2012-08-02T09:51:51.757 回答
0

You're starting with a string containing some HTML, stored in your txt variable. When you call $(txt) you're creating a jQuery object containing the elements defined in that HTML string, which is completely separate from your txt variable. You can then manipulate (in this case attempt to remove) elements, but since it's completely separate from txt the changes aren't going to be reflected in it.

If you want to change the value of txt to be something else, you'll need to assign that value back to it, possibly like so (you mentioned that calling .text() gave you what you expected/wanted to see):

txt = $(txt).find("select option[value='" + $(this).attr("id") + "']").remove().text();
于 2012-08-02T09:56:55.523 回答
0

remove() 方法删除元素 - 所以它们必须在 DOM 中,因为 txt 是一个变量,它没有在 DOM 中表示,所以值只是一个 string 。你应该使用像replace()这样的东西。

var txt = "<select name='example'><option value='1'>Test</option></select>";
        txt=txt.replace("<select name='example'><option value='1'>Test</option></select>","replacedText");
于 2012-08-02T10:02:14.063 回答