1

我想选择同名的输入,但出现语法错误:

$("input[name=$(this).prop('name')]"); 

但我可以通过$(this).prop('name').

编辑:

感谢您的所有回答。我认为他们都工作。但是谁能解释为什么开头和结尾的两个加号使jquery代码在字符串中解析?参考将不胜感激,谢谢

编辑2:

我知道加号用于字符串连接。但是在这种情况下,在第一个 + 之前或第二个 + 之后什么都没有。那么这里连接了什么?对不起,如果这个问题看起来太天真了

4

4 回答 4

4

应该是这样的:

$("input[name='"+$(this).prop('name')+"']"); 

jQuery 不解析字符串上的 jQuery 代码。要执行它,您应该将 jQueryprop()函数放在字符串之外。

于 2013-06-15T01:16:22.177 回答
3

But could anyone explain why the two plus sign at beginning and end make the jquery code parsed inside string?

Let's look at it step by step.

First, let's take the original approach:

$("input[name=$(this).prop('name')]"); 

The function "$" (which is an alias for jQuery) will get called with a string argument:

"input[name=$(this).prop('name')]"

jQuery will parse this string and interpret it like this:

/* 
Okay, I need to find an <input> 
that has an attribute "name", 
and the value of that attribute has to be, literally, "$(this).prop('name')". 
So, I'm looking for something that looks like this: */

<input name="$(this).prop('name')" />

However, what you probably meant to find was more like this:

<input name="some name, actually" />

(and "some name, actually" would be in the name property of $this at the point where you are making the original call)

Let's look at the new approach now:

When you write

$("input[name=" + $(this).prop('name') + "]");

You are constructing part of the string from your JavaScript objects. You are taking $(this) (which is a jQuery object), call its function "prop" to retrieve a property called "name", and using the output of that function in the new query. So if $(this).prop('name') returns "AWESOME", you are asking jQuery to find something that looks like this:

<input name="AWESOME" />

This should be more like what you were looking for!

于 2013-06-15T01:57:52.207 回答
2

您实际上是在寻找一个input名为 的元素$(this).prop('name')。你想要做的是这样写:

$("input[name="+$(this).prop('name')+"]"); 
于 2013-06-15T01:16:38.883 回答
2

尝试这样的事情:

$("input[name=" + $(this).prop('name') + "]");
于 2013-06-15T01:17:51.997 回答