2012-04-16 67 views
2

我想做一个复选框的形式,有鼠标悬停在图像和检查图像功能与jQuery。图像复选框与jQuery的形式

我成功地做了这个功能,但是工作不够好。

这里是我的html表单。

<label for="w_interest"> 
    <img src="/images/account/w_select.png_img"/ style='cursor:pointer;'> 
    <input name="w_interest" type="checkbox" id="w_interest" style="display:none"> 
</label> 

这里是jQuery的

$(document).ready(function() { 
    $('#img').hover(
    function() { 
     $(this).attr('src', '/images/account/ws_145_hover.png'); 
     }, 
    function() { 
     $(this).attr('src', '/images/account/ws_145.png'); 
     } 
); 

    $("#img").click(function() { 
    if(1) { 
     $(this).attr("src", "/images/account/ws_145_checked.png"); 
     $("#w_interest").val("0"); 
    } else { 
     $(this).attr("src", "/images/account/ws_145.png"); 
     $("#w_interest").val("1"); 
    } 
    }); 
}); 
  1. 当我点击图像,它将改为检查到的图像。但是,当我将鼠标移出时,它会更改为原始图像。我想确保它保持在检查图像。

  2. 我想确保它检查复选框的输入。

  3. 如果用户再次单击选中的图像,它将取消选择复选框输入。

你能帮我解决jquery问题吗?

回答

2

进行比较见下面的例子:http://jsfiddle.net/tErvQ/

代码:

$('.imag_box img').hover(
    function() { 
     if($(this).next().val() !== "1") { 
      $(this).attr('src', 'http://placehold.it/150/000000/fbaf5d'); 
     } 
     }, 
    function() { 
     if($(this).next().val() !== "1") { 
      $(this).attr('src', 'http://placehold.it/150/000000/ffffff'); 
     } 
    } 
); 


$(".imag_box img").click(function() { 
    if($(this).next().val() !== "1") { 
     $(this).attr("src", "http://placehold.it/150/000000/00ff18"); 
     $(this).next().val("1"); 
    } else { 
     $(this).attr("src", "http://placehold.it/150/000000/ffffff"); 
     $(this).next().val("0"); 
    } 
}); 

希望这就是你需要:)

使用被检查的属性可能是一个更好的主意,因为如果您提交表单,可能会在后处理中处理得更好。

+0

真棒!谢谢!! – james 2012-04-16 08:22:01

0

是错字,如果(1){

我想你应该与

if($("#w_interest").val() == 1) 
0

试试这个:

$(document).ready(function() { 
    var images = [ 
     '/images/account/ws_145.png', 
     '/images/account/ws_145_hover.png' 
    ]; 
    var $w_interest = $("#w_interest"); 
    var $img = $('#img'); 
    $img.hover(function() { 
     $img.attr('src', images[1]); 
    }, function() { 
     if($w_interest.val() == "0") { 
      $img.attr("src", images[0]); 
     } 
    }); 

    $img.click(function() { 
     if($w_interest.val() == "1") { 
      $img.attr("src", images[0]); 
      $w_interest.val("0"); 
     } else { 
      $img.attr("src", images[1]); 
      $w_interest.val("1"); 
     } 
    }); 
});