开发者

jQuery if statement problem

i am trying to change image in the div if the user click on any span,if div already contains roz variable(which comes from the index page) then by clickng on the span, img roz should not be appneded but it does not work.

i am not sure if the first part of IF statement in jQuery is right

here is html part

<div class="iconWrapper">
<ul class="color">
<li><a href="#" title="Selecteer"><span class="color1"></span></a> </li>
<li><a href="#" title="Selecteer "><span class="color2" ></span></a></li>
<li><a href="#" title="Selecteer"><span class="color3"></span></a> </l>
<li><a href="#" title="Selecteer"><span class="color4"></span></a></li>
</ul> </div>

<div id="div1" > <?php if(isset($_SESSION['img'])){
echo '<img src="' . $_SESSION['img'] . '" >' ; }
?>
<form method="post" action="weekDays.php">
<input name="kleur" type="text" value="" id="hiddencolor" />

<input name="submit" type="submit" value="Submit" />
</form> </div>

jQuery:

$(function(){
    var roz='../../photo/roz1.jpg';

    $('.iconWrapper span').click(function(e){
        var kleur=$(this).attr('class');
    if($('#div1').attr('src' == roz)){
        $('#div1' ).children('img').remove() ;
        $('#div1'). append('<img src="img/300.jpg" />');
    }else{
       $('#div1').children('img').remove();
       $('#div1').append('<img src="img/106.jpg" />');
    }
    e.preventDefault(); 
    alert(  $('#div1').html()  )开发者_运维知识库;       
});

});


if($('#div1').attr('src' == roz))

should be

if($('#div1').attr('src') == roz)


I'm thinking you actually want this:

$(function() {
    $('.iconWrapper span').click(function(e) {
        $('#div1').find('img').attr('src', function(index, src) {
            return src == '../../photo/roz1.jpg' ? 'img/300.jpg' : 'img/106.jpg';
        });
    });
    e.preventDefault();
});

Given that your current code seems to be looking for a src attribute on what I presume is a div.


The jQuery attr() is being used incorrectly. You need to use attr('src') to get the 'src' attribute and then compare it to your roz value.


try this:

$(function() {
    var roz = '../../photo/roz1.jpg';
    $('.iconWrapper span').click(function(e) {
        var kleur = $(this).attr('class');
        if ($('#div1').attr('src') == roz) {
            $('#div1').children('img').remove();
            $('#div1').append('<img src="img/300.jpg" />');
        } else {
            $('#div1').children('img').remove();
            $('#div1').append('<img src="img/106.jpg" />');
        }
        e.preventDefault();
        alert($('#div1').html());
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜