Javascript 使用jQuery在表单中选择图像

Javascript 使用jQuery在表单中选择图像,javascript,jquery,Javascript,Jquery,我有一些服务器端PHP代码,可以动态显示目录中包含的所有图像的缩略图: <form> <input type="hidden" name="animal"> <div id="thumbs"> \\ Dynamically created thumbnails start <img src="images/bat.jpg"> <img src="images/cat.jpg"> <img src=

我有一些服务器端PHP代码,可以动态显示目录中包含的所有图像的缩略图:

<form>
  <input type="hidden" name="animal"> 
  <div id="thumbs">
\\ Dynamically created thumbnails start
    <img src="images/bat.jpg">
    <img src="images/cat.jpg">
    <img src="images/rat.jpg">
\\ Dynamically created thumbnails end
  </div>
</form>

\\动态创建的缩略图开始
\\动态创建的缩略图结束
我需要正确的jQuery语法,以便当用户单击其中一个图像时:

  • 从所有缩略图中删除边框样式
  • 通过添加彩色边框高亮显示选定的缩略图
  • 将表单字段“animal”的值更改为图像中显示的文件名
非常感谢您的帮助。

如果“删除缩略图上的格式”意味着删除图像上的所有css,那么我认为您需要的是

如果“删除缩略图上的格式”意味着删除图像上的所有css,那么我认为您需要的是

演示:

jquery

$('#thumbs').delegate('img', 'click', function() {
    var $this = $(this);
    // Clear formatting
    $('#thumbs img').removeClass('border-highlight');

    // Highlight with coloured border
    $this.addClass('border-highlight');

    // Changes the value of the form field "animal" to the file name shown in the image.
    $('[name="animal"]').val( $this.attr('src').substring($this.attr('src').lastIndexOf('/')+1) );
    alert( $('[name="animal"]').val() );
});
css

我使用了
delegate
而不是
click
,因为您已声明图像将动态创建。

演示:

jquery

$('#thumbs').delegate('img', 'click', function() {
    var $this = $(this);
    // Clear formatting
    $('#thumbs img').removeClass('border-highlight');

    // Highlight with coloured border
    $this.addClass('border-highlight');

    // Changes the value of the form field "animal" to the file name shown in the image.
    $('[name="animal"]').val( $this.attr('src').substring($this.attr('src').lastIndexOf('/')+1) );
    alert( $('[name="animal"]').val() );
});
css


我使用了
delegate
而不是
click
,因为您已声明图像将动态创建。

什么是“清除格式”?对不起,“删除边框样式”更准确。将尝试编辑。什么是“清除格式”?对不起,“删除边框样式”更准确。将尝试编辑。先生,你太棒了。谢谢,先生,你真棒。非常感谢。