【问题标题】:Use jQuery toggleClass() when image inside a span tag is clicked单击跨度标记内的图像时使用jQuery toggleClass()
【发布时间】:2013-06-10 08:46:58
【问题描述】:

我正在使用 Razor 开发一个 ASP.NET MVC3 项目。我正在尝试实现一个简单的图片库。我的图片在 span 标签内,当点击图片时,我只想为点击的图片切换 span 标签的类别。

这是我的代码:

<span class="document-image-frame">
    @if (image != null) {
        <img src="file:\\105.3.2.2\upload\@image.Name" alt="docImg" />
    }
</span>

我试过这个脚本来切换:

$('.document-image-frame img').click(function () {
    $(this).toggleClass();
})

它不工作。我猜在这种情况下$(this) 是图像本身而不是跨度标记,但是如果我尝试$('.document-image-frame').toggleClass(); 当我只想切换单击图像的跨度的样式时,我会丢失所有跨度标记的样式。

这是生成的 HTML:

<span class="document-image-frame">>
    <img src="file:\\105.3.2.2\upload\\10007\Desert.jpg" alt="docImg" />
</span>

【问题讨论】:

    标签: javascript jquery css asp.net-mvc-3 razor


    【解决方案1】:

    试试这个:

     $(this).parent().toggleClass();
    

    或者这个:

    $(this).parent().toggleClass("document-image-frame");
    

    如果有效,请阅读:http://api.jquery.com/parent/

    【讨论】:

    • 在他接受答案之前有一个超时时间。另外,不带参数的 .toggleClass() 有什么作用?
    • @Cherniv 一切都很简单,你只需要知道怎么做;)
    • @Cherniv 啊,显然它会切换它在元素上找到的所有类名。可能很方便:) +1
    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    相关资源
    最近更新 更多