jquery树遍历prev()问题

发布于 2024-08-26 20:37:28 字数 670 浏览 2 评论 0原文

我喜欢单击标签并选中前面的复选框。 我已经尝试了下一个代码,但这不起作用。我已经尝试了 2 个小时,但我错过了什么?

JQUERY

jQuery(document).ready(function() {
    $('.namelabel').live('click', function() {
        if ($(this).prev("input:checked").val() != null) {
            $(this).prev("input").removeAttr("checked");
        } else  {
            $(this).prev("input").attr("checked","checked"); 
        }
    });
});

HTML
<input type="checkbox" class="check" name="example" /> <img src="image.png" class="modelinfo" /> <label class="namelabel">John Doe</label>

谁能帮我解决这个问题?非常感谢!

ps 我知道我可以使用 标签轻松解决这个问题,但这不是问题。

I like to click a label and check the previous checkbox.
I've tried the next code, but this is not working. I have tried for 2 hours, but what am i missing?

JQUERY

jQuery(document).ready(function() {
    $('.namelabel').live('click', function() {
        if ($(this).prev("input:checked").val() != null) {
            $(this).prev("input").removeAttr("checked");
        } else  {
            $(this).prev("input").attr("checked","checked"); 
        }
    });
});

HTML
<input type="checkbox" class="check" name="example" /> <img src="image.png" class="modelinfo" /> <label class="namelabel">John Doe</label>

Who can help me to solve this question? Many thanks!

p.s. I know i can easy solve this with the <label for=""> tag, but that is not the question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾忌 2024-09-02 20:37:28

你可以这样做:

$('.profilename').live('click', function() {
  var cb = $(this).prevAll(":checkbox:first");
  cb.attr("checked", !cb.is(":checked")); 
});

另外,刚刚注意到你的类不匹配,在你的 html 中它是 namelabel 但在你的 jQuery 中它是 profilename,它是一个不同的例子还是他们应该匹配吗?

You can do it like this:

$('.profilename').live('click', function() {
  var cb = $(this).prevAll(":checkbox:first");
  cb.attr("checked", !cb.is(":checked")); 
});

Also, just noticed your class doesn't match, in your html it's namelabel but in your jQuery it's profilename, is it a different example or should they match up?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文