1

我的 php 脚本为该图像放置了一个带有隐藏复选框的图像。单击图像时,其复选框设置为选中。然后我想在图像周围放置一个轮廓以显示图像被选中,而无需显示丑陋的复选框。为此,我创建了一个名为 $i 的 php var,它为每个输出的图像递增以充当图像 id,然后将 id 传递给 Javascript 函数并作为 jquery 选择器调用。

所有这一切都很好,但是当调用 toggleClass 事件时,它会以一种我以前从未经历过的方式进行。它不会在第一次点击时触发,但第二次会导致图像的突出显示与复选框的检查不同步,即

图片 > 点击 = 无高亮 || 复选框选中。

图片 > 第二次点击 = 图片突出显示 || 复选框未选中。

如果 addClass 事件被调用,那么它会起作用,在第一次点击时突出显示。但是当重写以删除第二次单击时的突出显示时,原始问题又回来了。(我使用带有.hasClass()的if else语句来做到这一点,如果类'highlight'删除它,否则addclass highlight ...)

变量似乎没有问题,因为仅用 HTML 和 JS 中的数字 1 替换这些变量,问题仍然存在。

直接使用我正在使用的代码:

(例如,假设 php var $i 为 1,因为当这部分工作正常时,写出 for 循环等似乎有点毫无意义[当按钮时,锚的 href="" 也将被阻止被跟踪单击,从而使突出显示成为可能,此代码尚未编写,因此不会引起问题,我只是删除了 href='' 用于测试])

HTML / PHP

// for this exmaple $i = 1;
// $id is the images unique id, the one used in the server for the image path


<a class='selectbox' id='hil' style='position:relative;' href='show-image.php?id=$id'>
    <div style='display:inline-block; padding:15px;' id=\"$i\" onclick=\"highlight('" . $i . "')\"  class='lifted drop-shadow-sq' >
        <label for=\"$id\">
            <img class='reflect reflect-br' width='150px;' height='150px' src=\"thumb.php?id=$id\">
        </label>
            <input id=\"$id\" style='display:non;' type='checkbox' class=\"show-man\" name='images[]' value='$id'>
    </div>
</a>

jQuery

function highlight(x) { 
id = x;
    $('#' + id).click(function() {
        $(this).toggleClass('highlight');
    });
}

CSS

.highlight img {
box-shadow:0 0 10px #5bb1ce;
}

感谢您提前回复。

4

2 回答 2

1

您的highlight()函数将单击事件绑定到 div 元素。因此,第一次单击将绑定事件,第二次单击将实际执行代码。您可以通过两种方式更改它

由于您是 uisngonclick属性,因此您可以将突出显示功能更改为如下所示

function highlight(x) { 
  id = x;
  $('#' + id).toggleClass('highlight');
}

或者在页面加载后删除onclick属性和绑定事件(我假设所有 div 都提升了类

$(document).ready(function(){
  $('.lifted').on('click', function(){
    $(this).toggleClass('highlight');
  });
});
于 2012-10-25T19:54:06.250 回答
0

对,经过几个小时的挠头和拉头发后,我找到了解决方案。似乎我用来检查和取消选中复选框是导致问题的原因。不知道为什么?

所以我删除了它并为突出显示创建了一个简单的 Jquery 函数。(为了感谢 Zefiryn,这是对他的回复的轻微修改。)

$(document).ready(function(){
    $(".lifted").live('click', function() {
        $(this).toggleClass("highlight");
    });
});

然后,我从 html 中删除了标签,并使用复选框 id 中的图像唯一 id 将它们替换为 JavaScript 函数,以选中/取消选中复选框。

<div style='display:inline-block; padding:15px;' id=\"$i\" onclick=\"if (event.target.tagName != 'INPUT') document.getElementById('$id').checked = !document.getElementById('$id').checked\"  class='lifted drop-shadow-sq' >
    <img class='reflect reflect-br' width='150px;' height='150px' src=\"thumb.php?id=$id\">
        <input id=\"$id\" style='display:none;' type='checkbox' class=\"show-man\" name='images[]' value='$id'>
</div>

CSS保持不变。

现在一切似乎都已排序并且工作正常,最后我必须感谢 Zefiryn 的上述帮助。

于 2012-10-25T21:05:42.323 回答