jquery 输入值选择器
我这里有代码..
<div>
<input type="hidden" value="hello" />
</div>
<div>
<input type="hidden" value="world" />
</div>
是否可以选择内部值为“hello”的div并将所选div的颜色更改为红色...?
$("div input[value='hello']").css("background","red"); //i have this in mind
//but i think its wrong:D
请帮忙..
i have here the code..
<div>
<input type="hidden" value="hello" />
</div>
<div>
<input type="hidden" value="world" />
</div>
is it possible to select the div with the value "hello" inside and change the selected div's color to red...?
$("div input[value='hello']").css("background","red"); //i have this in mind
//but i think its wrong:D
any help please..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您想要选择输入,然后获取其父
div
:You want to select the input, then take its parent
div
:正如以后遇到此问题的人的注释一样,当将特定
值
作为属性(即在HTML中硬编码的属性)进行搜索时,这些答案是正确的- 根据所提出的问题完全正确。但是,如果用户在任何时候更改了字段的值,则属性值不会更新,而只会更新元素的属性值。这将导致意外的行为,以选择实际上具有不同当前值的元素的形式...相反 - 或者至少在我找到更好的方法之前 - 我一直在使用以下内容:上面创建了一个新的 jQuery 伪选择器,可以这样使用:
它将选择以值“test”开头的所有输入,或者:
它将选择其值中任何位置包含“test”的所有输入。
还支持
!
不、$
结尾或=
等于...Just as a future note to those that come across this question, these answers are correct for when searching for the specific
value
as an attribute i.e. the one hard-coded in the HTML — completely correct as per the question asked. However, if the value of the field is changed by the user at any point the value attribute is not updated, only the element's value property. This will lead to unexpected behaviour in the form of selecting elements that actually have different current values... instead — or at least until I find a better way — I've been using the following:The above creates a new jQuery pseudo selector, which can be used like so:
Which will select all inputs that start with the value "test", or:
Which will select all inputs that contains "test" anywhere in it's value.
Also supported are
!
not,$
ends with or=
equals...这样做:
实例
或者,如果“颜色”实际上是指“背景颜色”:
实例
This does it:
Live example
Or if by "color" you really meant "background color":
Live example
出于提供信息的目的将其扔在那里。
在实践中,我会使用 @BoltClock's 或 @TJ Crowder 的 解决方案。
这使用
has-selector
(docs)< /i> 选择具有作为直接后代的
元素。
我更喜欢其他的原因是因为他们使用相当简单的有效 CSS 选择器。这是一个有效的替代方案,但可能执行速度会慢一些。
Throwing this out there for informational purposes.
In practice I'd use @BoltClock's or @T.J. Crowder's solutions.
This uses the
has-selector
(docs) to select<div>
elements that have a<input value="hello">
as a direct descendant.The reason I'd prefer the others is because of the fairly simple valid CSS selectors they use. This is a valid alternative, but will likely perform a little slower.
以上答案的 @pebbl 的咖啡脚本版本。
Coffee script version of @pebbl above answer.