While-loop with Javascript and JQuery UI failes
I use the JQuery UI Library and the Dialog
function.
I would like to create more than one triggers inside my javascript.
This is my original JS:
$j(function() {
$j( "#dialog1" ).dialog({
autoOpen: false,
show: "slide",
hide: "explode"
});
$j( "#dialog2" ).dialog({
autoOpen: false,
show: "slide",
hide: "explode"
});
...
$j( ".opener1" ).click(function() {
$j( "#dialog1" ).dialog( "open" );
return false;
})
$j( ".opener2" ).click(function() {
$j( "#dialog2" ).dialog( "open" );
return false;
})
...
});
I need at least a dozen of those triggers. So, I though, let's make a php While
loop.
<?php
$i = 1;
while ($i <= 10) {
echo '$j( "#dialog'.$i.'" ).dialog({
autoOpen: false,
show: "slide",
hide: "explode"
});';
$i++;
}
$q = 1;
while ($q <= 10) {
echo '$j( ".opener'.$q.'" ).click(function() {
$j( "#dialog1" ).dialog( "open" );
开发者_开发百科 return false;
})';
$q++;
}?>
And for the first while
, it's all working just fine. It does the trick. But for the second while
, the page just ignores the whole JS/PHP block...
What am I doing wrong?
This line in your second while loop:
$j( "#dialog1" ).dialog( "open" );
Should that not be:
$j( "#dialog' . $q . '" ).dialog( "open" );
At the moment all of your click handlers will open #dialog1 which I guess is not what you're trying to do
You could do the whole thing in js though as suggested above:
for (var i=1;i<=10;i++) {
$j('#dialog' + i).dialog({
autoOpen: false,
show: "slide",
hide: "explode"
});
$j('.opener' + i).click(function() {
$j( "#dialog" + i).dialog( "open" );
return false;
}
}
You could generate all of the above using only jQuery by linking all the dialogs using one class (which will become their selector) and link the openers with their respective dialogs as found in the example below:
http://jsfiddle.net/Awh7D/
Note: Better ways to link the openers with their respective dialogs can be developed.
At least in the first case you should be able to use "multiple selectors", like in
$j( "#dialog1, #dialog2, #dialog3" ).dialog({
autoOpen: false,
show: "slide",
hide: "explode"
});
EDIT (after a "working break")
the second part, where you reference the object inside the function, should work like this:
$j( ".opener1, .opener2, .opener3" ).click(function() {
$j(this).dialog( "open" );
return false;
});
Sorry I can't simulate that right now, so it's a bit walking on thin ice - you will forgive me.
I agree with Clive :
$q = 1;
while ($q <= 10) {
echo '$j( ".opener'.$q.'" ).click(function() {
$j( "#dialog1" ).dialog( "open" );
return false;
})';
$q++;
}?>
Should be :
$q = 1;
while ($q <= 10) {
echo '$j( ".opener'.$q.'" ).click(function() {
$j( "#dialog'.$q.'" ).dialog( "open" );
return false;
})';
$q++;
}?>
You could also share a class amongst the dialogs/openers. Here's a fiddle example
http://jsfiddle.net/ZbMcA/
精彩评论