使用 jQuery 查找所选选项的名称
我制作了一个 jquery/ajax 函数来更新 #courses,发送 #fos 的 .val() 和 .text(),特别是所选的函数,如下所示:
$('#selling #fos').change(function() {
$.post('/ajax/courses',
{
fos_id: $('#selling #fos').val(),
name: $('#selling #fos :selected').text()
},
function(data) {
$('#selling #courses').html(data);
});
});
How do I Extend this function so that it use 'this ',允许我在同一页面上多次重用此函数吗?我被抓住了,因为你不能使用 name: $(this + ' :selected').text()
。
I've made a jquery/ajax function that updates #courses, sending #fos's .val() and .text(), specifically of the one that is selected, like so:
$('#selling #fos').change(function() {
$.post('/ajax/courses',
{
fos_id: $('#selling #fos').val(),
name: $('#selling #fos :selected').text()
},
function(data) {
$('#selling #courses').html(data);
});
});
How do I extend this function so that it uses 'this', allowing me to reuse this function multiple times on the same page? I'm caught because you can't use name: $(this + ' :selected').text()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该有效:
它不漂亮,但它确实有效:)
或者这会有效:
This should work:
it's not pretty but it does the trick :)
or this will work:
我认为您正在寻找的是 .filter()
如果未选择它,它将返回空字符串
好运气!
编辑:
我没有看到Brett在“:selected”之前有一个空格,这意味着他正在寻找一个孩子。 Stefanvds 建议使用 find() 会很好地工作。
filter() 检查当前 dom 是否为“:selected”,而 find() 将查找所有级别的子级。如果您知道要查找的选定 dom 是直接的,您也可以使用 .children() “this”的子级,因为它效率更高,因为您只寻找一级子级。
I think what you are looking for is .filter()
It will return empty string if it's not selected
Good luck!
Edit:
I didn't see that Brett had a space before ":selected" which means he is looking for a child. Stefanvds suggestion to use find() will work fine.
filter() checks if the current dom is ":selected" while find() is going to look for the children on all levels. You could also use .children() if you know that the selected dom you are looking for is a direct child of "this" as it is a lot more efficient since you are only looking for one level of children.
没有 jQuery
没有 jQuery 的情况下做到这一点非常简单。在
change
事件侦听器内,可以使用this.options[this.selectedIndex]
访问所选选项。从那里,您可以访问所选选项元素的value
/text
属性。此处示例
Without jQuery
It's pretty simple to do this without jQuery. Inside of a
change
event listener, the selected option can be accessed usingthis.options[this.selectedIndex]
. From there, you can access thevalue
/text
properties of the selected option element.Example Here
您还可以使用 jQuery 的第二个参数(上下文)来避免不必要的“过滤器”、“查找”、“子项”等。这允许您的选择器类似于:
You can also use jQuery's second argument (context) to avoid the unnecessary "filter", "find", "children" etc. This allows your selector to be something like: