jQuery:如果选择元素存在则执行某些操作
嘿,我在 Stack Overflow 上四处查看,并尝试了其他一些人的尝试,但我就是无法让它发挥作用。
我有一个像这样的选择元素:
<select id="slct_firstCat" name="slct_firstCat" size="15">
</select>
这仅在特定的 AJAX 请求完成后显示,因此该选择元素不会随原始页面的 DOM 一起加载,而是在主页加载后作为单独的 AJAX 请求加载。
我基本上想这样做......
if (/* select element exists */) {
// Then change the colour of a div to green
} else {
// Change the colour to red
}
但请记住,这必须在页面加载后起作用。如果需要,我可以单击选择来运行 JS 函数。
我尝试了下面的代码,但无法让它工作:
if ($(".element1").length > 0 || $(".element2").length > 0 {
// code
}
所以基本上,如果选择元素存在,则将选项卡颜色更改为绿色,否则将其更改为红色。
Hey, I looked around on Stack Overflow and tried a few other people's attempts at this, and I just couldn't get this to work.
I have a select element like this:
<select id="slct_firstCat" name="slct_firstCat" size="15">
</select>
This only shows once a specfic AJAX request has completed, so this select element is NOT loaded with the original page's DOM, it is loaded as a seperate AJAX request after the main page has loaded.
I basically want to do this...
if (/* select element exists */) {
// Then change the colour of a div to green
} else {
// Change the colour to red
}
But remember, this has to work after the page has loaded. I can click the select to run the JS function if needed.
I tried this code below, but couldn't get it to work:
if ($(".element1").length > 0 || $(".element2").length > 0 {
// code
}
So basically, if the select element exists, then change the tab colour to green, else change it to red.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须将代码放入
jQuery.ajax()
的成功回调中。并且>
,因为与 Ruby 不同,$('.element1').length > 中不需要 0
部分00
和""
也是 JavaScript 中的虚假。You have to put your code in
jQuery.ajax()
's success callback. And the> 0
part isn't needed in$('.element1').length > 0
, since—unlike in Ruby—,0
and""
are also falsy in JavaScript.您可以尝试使用类似的东西:
You can try to use something like:
将您的 if 块移至 ajax success 它将起作用,
只是举个例子
move your if block to ajax success it will work
just giving an example
当事件发生时,即当 ajax 调用成功、开始或触发另一个事件时,您应该更改颜色。无论如何,您可以使用此代码,这不是最好的方法,但适合您的需求:
You should change the colours when your events happen, i.e. when your ajax call succeeds, starts, or when you trigger another event. Anyway, you could use this code, that isn't the best way to do it, but suits your needs: