jquery 查找具有动态值的选项

jquery find option with dynamic value

对于 node.js 应用程序,我有一个包含以下代码的 ejs 文件:

<script type="text/javascript">
                //triggered when modal is about to be shown
                $('#editNodeModal').on('show.bs.modal', function(e) {

                    var nodeGroups = $(e.relatedTarget).data('groups-id');
                    //alert(nodeGroups);

                    $(e.currentTarget).find('#nodeGroup option[value="???"]').attr("selected", "selected");

                });
</script>

此代码从当前页面获取一些数据以自动 select 模式 select 列表中的选项。如果我更换???使用我的 select 列表中现有选项的值,它有效。

我的问题是:

我想更换???使用 nodeGroups 值,但我不知道该怎么做... 有人可以帮助我吗?

非常感谢!

您可以简单地将 nodeGroups 值连接到您的选择器字符串中:

var nodeGroups = $(e.relatedTarget).data('groups-id');
$(e.currentTarget)
   .find('#nodeGroup option[value="' + nodeGroups + '"]')
   .attr("selected", "selected");

对于它的价值,您可以通过一些调整来更新您的代码 jQuery-wise,同时缩短它:

$('#nodeGroup option[value="' + nodeGroups + '"]', e.currentTarget).prop("selected", true);

以上基本就是:

$('selector', context);

相同
$(context).find('selector');

.attr() 的使用在 jQuery 1.7 中发生了变化,引入了 .prop()selectedoption 个元素的 属性,因此应更改为 .prop()