我想知道我是否可以一起使用查询和javascript,所以我可以用javascript选择一个元素,然后使用javascript来处理该元素.对不起,如果那没有意义.这是一个例子:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
Run Code Online (Sandbox Code Playgroud)
如果不是这样,我将如何使用常规javascript逐个获取元素.谢谢!
编辑:我知道JQUERY是JavaScript,但我想知道我是否可以混合jquery选择器和javascript'控制器' - 失去一个更好的词
要按照要求回答您的问题,有几种方法可以获取jQuery对象,即返回的内容$('some selector'),并获取对底层DOM元素的引用.
您可以访问单个DOM元素,如数组元素:
// update the src of the first matching element:
$(".nav_flag")[0].src = "images/flags/"+userCountryLower+".gif";
// if you're going to access more than one you should cache the jQuery object in
// a variable, not keep selecting the same thing via the $() function:
var navFlgEls = $(".nav_flag");
for (var i = 0; i < navFlgEls.length; i++) { ... }
Run Code Online (Sandbox Code Playgroud)
但是当你可以使用jQuery的.each()方法时,你不会手动循环遍历元素,注意在你提供的回调函数this中将设置为当前的DOM元素:
$(".nav_flag").each(function() {
this.src = "images/flags/"+userCountryLower+".gif";
});
Run Code Online (Sandbox Code Playgroud)
但是,jQuery提供了一种使用一行代码设置属性的方法:
$(".nav_flag").attr("src", "images/flags/"+userCountryLower+".gif");
Run Code Online (Sandbox Code Playgroud)
要回答你问题的第二部分,在没有jQuery的情况下做同样的事情,你可以使用.getElementsByClassname()或者.querySelectorAll()如果你不关心支持旧的浏览器.