jQuery 表单输入按 id 选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5716021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:42:22  来源:igfitidea点击:

jQuery form input select by id

jquery

提问by Sevenearths

Code

代码

<form id='a'>
  <input id='b' value='dave'>
</form>

Question

How do I get the value from input 'b' while at the same time make sure it is inside 'a' (something like $('#a:input[id=b]')).

我如何从输入 'b' 中获取值,同时确保它在 'a' 内(类似于$('#a:input[id=b]'))。

I only ask because I might have other inputs called 'b' somewhere else in my page and I want to make sure I'm getting the value from the correct form.

我之所以这么问,是因为我的页面中的其他地方可能还有其他名为“b”的输入,我想确保我从正确的表单中获取了值。

回答by Vincent Ramdhanie

You can do that using the descendant selectors:

您可以使用后代选择器来做到这一点:

 $("#a #b")

However, id values are supposed to be unique on a page.

但是,id 值在页面上应该是唯一的。

回答by Andrew Orsich

For example like this:

例如像这样:

var value = $("#a").find("#b").val()

回答by Guffa

You can just target the id directly:

您可以直接定位 id:

var value = $('#b').val();

If you have more than one element with that id in the same page, it won't work properly anyway. You have to make sure that the id is unique.

如果同一页面中有多个具有该 ID 的元素,则无论如何它都无法正常工作。您必须确保 id 是唯一的。

If you actually are using the code for different pages, and only want to find the element on those pages where the id:s are nested, you can just use the descendant operator, i.e. space:

如果您实际上是将代码用于不同的页面,并且只想在 id:s 嵌套的那些页面上查找元素,则可以使用后代运算符,即空格:

var value = $('#a #b').val();

回答by Spudley

If you have more than one element with the same ID, then you have invalid HTML.

如果您有多个具有相同 ID 的元素,则您的 HTML 无效。

But you can acheive the same result using classes instead. That's what they're designed for.

但是您可以使用类来获得相同的结果。这就是它们的设计目的。

<input class='b' ... >

You can give it an ID as well if you need to, but it should be unique.

如果需要,您也可以给它一个 ID,但它应该是唯一的。

Once you've got the class in there, you can reference it with a dot instead of the hash, like so:

一旦你在那里得到了这个类,你可以用一个点而不是散列来引用它,就像这样:

var value = $('#a .b').val();

or

或者

var value = $('#a input.b').val();

which will limit it to 'b' class elements that are inputs within the form (which seems to be close to what you're asking for).

这会将它限制为表单中输入的 'b' 类元素(这似乎与您要求的很接近)。

回答by good_evening

Why not just:

为什么不只是:

$('#b').click(function () {
    var val = $(this).val(); 
})

Or if you don't click it (and I guess you won't) and you will use submit button, you can use prev()function either.

或者,如果您不单击它(我猜您不会单击它)并且您将使用提交按钮,您也可以使用prev()函数。