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>
开发者_StackOverflow社区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.
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.
jQuery.ajax({
url: 'example.php',
success: function () {
if ($('#slct_firstCat').length) {
$('#myDiv').css('color', 'green');
} else {
$('#myDiv').css('color', 'red');
}
});
You can try to use something like:
if ($('select#slct_firstCat').length) {
// ... stufff....
}
move your if block to ajax success it will work
just giving an example
$.ajax({
url: "test.html",
context: document.body,
success: function(){
if ($(".element1").length > 0 || $(".element2").length > 0 {
...stuff...
}
}
});
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:
$(document).ready(function(){
setInterval(function(){
if($("#slct_firstCat").size() > 0)
$("#divColour").css("backgroundColor", "green");
else
$("#divColour").css("backgroundColor", "red");
}, 100);
});
精彩评论