Using jQuery attr() what would be the proper syntax to pass a variable in as the value. What I am trying to do is :
var under700 = 'image.jpg'
$('.two_images img').attr('src', (under700) );
Edit
Judging from the responses, I may have oversimplified this. Here is the rest of the function if that adds any clarity.
$(document).ready(function() {
function imageresize() {
var contentwidth = $('#two_up').width();
var under700 = '<?php bloginfo('template_url'); ?>/scripts/timthumb.php?src=<?php echo $image_img_tag[0] ?>&w=340'
if ((contentwidth) < '700'){
// I also tried defining the variable here
$('.two_images img').attr('src', under700 );
} else {
// this one works fine
$('.two_images img').attr('src','<?php echo $image_img_tag[0] ?>');
}
}
imageresize();//Triggers when document first loads
$(window).bind("resize", function(){//Adjusts image w开发者_如何转开发hen browser resized
imageresize();
});
$('.two_images img').attr('src', under700);
Don't need the inner brackets, although they won't stop it working.
Have you tried the code without the php? It looks like you might have some issues with too many single quotes on that line, but it's hard to tell without seeing the rest of the document.
Try replacing the php echos with just plain strings, eg: var under700 = '123';
, and make sure you end the variable declaration line with a semi colon, it looks like that might be missing too, and can cause odd errors.
I believe this line is wrong:
if ((contentwidth) < '700'){
jQuery's width()
function returns an integer, so you don't need the quotes around the 700
:
if(contentwidth < 700) {
Try that.
<script>
// declare early
function imageresize() {
var contentwidth = $('#two_up').width();
// double quoted: "template_url" and missing ; at the end of line
var under700 = '<?php bloginfo("template_url"); ?>/scripts/timthumb.php?src=<?php echo $image_img_tag[0] ?>&w=340';
// extra parentheses for contentwidth are not necessary
if (contentwidth < 700)
$('.two_images img').attr('src', under700 );
else
$('.two_images img').attr('src','<?php echo $image_img_tag[0] ?>');
}
// run after document is ready
$(document).ready(function() {
imageresize();
});
</script>
Dummy example:
<?php
// test.php
function bloginfo($a) {
echo "http://somebloginfo.com/qwerty";
}
$image_img_tag = array("someimagtag.jpg");
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>
function imageresize() {
var contentwidth = $('#two_up').width();
var under700 = '<?php bloginfo("template_url"); ?>/scripts/timthumb.php?src=<?php echo $image_img_tag[0] ?>&w=340';
if (contentwidth < 700)
$('.two_images img').attr('src', under700 );
else
$('.two_images img').attr('src','<?php echo $image_img_tag[0] ?>');
}
$(document).ready(function() {
imageresize();
});
</script>
</head>
<body>
test
<div id='two_up' style="width: 400px;"></div>
<div class="two_images">
<img />
<img />
</div>
</body>
</html>
精彩评论