在不同的 div 中选择类似名称的元素?
假设我的页面中有以下 div:
<div id="person_1">
Name: <span>Bob</span> <br>
Gender: <span>Male</span>
</div>
<div id="person_2">
Name: <span>Sally</span> <br>
Gender: <span>Female</span>
</div>
如果我想更新人员 1 的姓名或性别,我想不出任何方法来选择该范围,除非我将范围更改为:
<span id="person_1_name">Bob</span>
<span id="person_1_gender">Male</span>
并且:
<span id="person_2_name">Sally</span>
<span id="person_2_gender">Female</span>
然后我可以执行:$("#person_1_name").html(bob.newName);
。然而,这非常丑陋,不是我的偏好。
有没有办法做这样的事情?
$("#person_1 name").html(bob.newName);
$("#person_1 age").html(bob.newAge);
$("#person_2 name").html(sally.newName);
$("#person_2 age").html(sally.newAge);
Say I have the following divs in my page:
<div id="person_1">
Name: <span>Bob</span> <br>
Gender: <span>Male</span>
</div>
<div id="person_2">
Name: <span>Sally</span> <br>
Gender: <span>Female</span>
</div>
If I wanted to update the name or gender of person 1, I can't think of any way to select that span, except if I changed the spans to:
<span id="person_1_name">Bob</span>
<span id="person_1_gender">Male</span>
And:
<span id="person_2_name">Sally</span>
<span id="person_2_gender">Female</span>
And then I could do: $("#person_1_name").html(bob.newName);
. However, that's very ugly and not my preference.
Is there a way to do something like this?
$("#person_1 name").html(bob.newName);
$("#person_1 age").html(bob.newAge);
$("#person_2 name").html(sally.newName);
$("#person_2 age").html(sally.newAge);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还可以执行以下操作而不是使用类
You can also do the following instead of using classes
您可以使用类来标识您的 span 元素,如下所示:
然后您可以像这样编写代码:
或者,您可以将
标记更改为
或
标签,但这不符合 HTML,并且您现在或将来可能会遇到各种跨浏览器问题,因此我不推荐它。You can use classes to identify your span elements, like this:
And then you code like this:
Alternatively, you could change your
<span>
tags to<name>
or<age>
tags, but this isn't HTML compliant, and you could run into all kinds of cross browser issues now or in the future, so I wouldn't recommend it.为什么不使用:
那么用于选择人员 1 的姓名的 jquery 将是
Fiddle 示例: http:// jsfiddle.net/zSqjV/1/
否则,如果您不想更改 HTML 并且您知道 name 始终是 div 中的第一个 span,gender 始终是最后一个 span在div中,你可以使用这个:
Why not use:
Then the jquery for selecting the name for person 1 would be
Fiddle example: http://jsfiddle.net/zSqjV/1/
Otherwise, if you don't want to change the HTML and you know that name will always be the first span in the div and gender will always be the last span in the div, you can use this: