简体   繁体   English

如何从js函数参数值获取动态的JQuery Selector?

[英]How to get a dynamic JQuery Selector from js function parameter value?

I have this javascript function and i qould to create a jquery selector, which was build from js function parameter value: 我有这个javascript函数,我可以创建一个jQuery选择器,它是从js函数参数值构建的:

function myJSFunction(elementId){
    var showSomeData= {
        'value_1': 'abc',
        'value_2': 'xyz'
    };

    var selector = "[name=" + elementId + "] option";
    jQuery("'" + selector + "'").each(function() {
         $(this).attr('title', showSomeData[$(this).val()]);
    });
}; 

But this kind of code doesn´t work. 但是这种代码行不通。 If i set the concrete value, which i can see in the html dom by using firebug, this code works fine. 如果我设置了具体的值(可以使用Firebug在html dom中看到),则此代码可以正常工作。 What was my mistake? 我怎么了

而不是使用$("'" + selector + "'")而是使用$(selector)来解决您的问题。

As stated in comments, you don't need "'" again to find the elements, use directly : jQuery(selector) : 如评论中所述,您无需再次使用"'"来查找元素,直接使用jQuery(selector)

var selector = "[name=" + elementId + "] option";
jQuery(selector).each(function() {
    $(this).attr('title', showSomeData[$(this).val()]);
});

remove Quotes 删除行情

 var selector = "[name=" + elementId + "] option";
    $(selector).each(function(i,val) {


    });

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM