jquery查找具有动态值的选项

时间:2015-01-02 21:52:30

标签: jquery node.js

对于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>

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

我的问题是:

我想替换???使用nodeGroups值但我不知道如何做到这一点...... 有人能帮助我吗?

非常感谢你!

1 个答案:

答案 0 :(得分:1)

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

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

对于它的价值,您可以通过几次调整将您的代码更新为jQuery,并同时缩短它:

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

以上基本上是:

$('selector', context);

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

在引入.attr()的jQuery 1.7中使用了.prop()selectedoption元素的属性,因此应使用.prop()进行更改。