0

这是我的问题,我想选择一张图片并使用 jquery 提交,所以我有不同的图片,我选择一个并提交。

所以我的想法是,当我单击 LabBox 中的某个图像时,例如“images/dontlike_OFF.png”,我创建一个选择属性($(this).attr('select', 'true');稍后,当我单击时,sendLabForm我想获取我拥有的图像的名称使用选择器点击$(#LabBox img[attribute=Value])

我相信这个创建属性的想法很奇怪,但我真的可以看到,在萤火虫上,该属性确实被创建了,问题只是当我想用所选属性获取该 img 的名称时。

所以,我的问题是:为什么这是不可能的?当我单击提交按钮而不使用通常的 html 表单时,有什么方法可以获取我选择的 img 的名称?

<div id='LabBox'>
    <img alt="dontlike" name="dlike" src="images/dontlike_OFF.png"/>
    <img alt="check" name="check" src="images/check_OFF.png"/>
    <img alt="funny" name="funny" src="images/funny_OFF.png"/>
    <img alt="idea" name="gidea" src="images/idea_OFF.png"/>
    <img alt="imp" name="imptt" src="images/imp_OFF.png"/>
 </div>   
    <script type="text/javascript">

        $("#LabBox img").click(function () {
                $(this).attr('select', 'true');     
            });

        $("#sendLabForm").click(function(){
            console.log($("#LabBox img[select='true']").name);     
        });


    </script>
4

4 回答 4

2

您应该使用 data(),如下所示:

演示

$("#LabBox img").click(function () {
     $(this).data('select', true);
 });

 $("#sendLabForm").click(function () {
     var selectedImgs = [];
     $("#LabBox img").each(function () {
         $(this).data('select') ? selectedImgs.push(this.name) : false;
     });
     alert(selectedImgs.join(','));
 });
于 2013-04-17T16:11:10.470 回答
1

您应该做的是创建与图像关联的复选框列表(或使用 data 属性,如下所述)。如果您希望用户单击图像,您可以隐藏复选框,只需在图像和复选框之间创建关联。当您提交表单时,复选框值中的图像 url 字符串被提交。

你不应该的是发明属性。

于 2013-04-17T15:53:27.067 回答
0

这是我的问题的解决方案。实际上,您可以创建属性,您只需指定.attr()获取它们的方法。

这真的有效。

$("#LabBox img").click(function () {

        $(this).attr('select', true);
});


$("#sendLabForm").click(function(){

    console.log( $('#LabBox img[select="true"]').attr('name'));

    });

目前我认为这种方法没有任何缺点,但如果您发现这种方法有任何问题,请告诉我。

于 2013-04-17T17:51:42.183 回答
0

为什么不简单地给选定的图像一个类别?

$('#LabBox img').click(function(e){
    $(this).toggleClass('active');
});

$('form').submit(function(){
    console.log( $('#LabBox img.active') );
});
于 2013-04-17T17:05:06.210 回答