jQuery父子元素点击事件

发布于 2025-01-05 10:15:50 字数 826 浏览 4 评论 0原文

我的 HTML 看起来像这样(不幸的是它无法更改,因为它是使用我正在使用的 CMS 呈现的)

<li>
<input id="cb1" type="checkbox">
<label for="cb1">
<div>Some Other Content</div>
<div class="pledge">Click to Pledge</div>
</label>
</li>

$("div.pledge").click(function() {

  var checkboxlabel = $(this).parent("label");

  $("input[for=checkboxlabel]").attr('checked', !$checkbox.attr('checked'));

});

如果我单击标签内的任意位置,使用此代码将切换复选框。我需要的是仅当我单击

元素时才发生该操作。我怀疑 .stopPropagation();会在这里帮助我,但我无法让它正常工作。

这是另一个似乎实现相同想法的镜头:

$("div.pledge").click(function() {

  $("input[for=' + this.parent("label").attr("id") + ']").attr('checked', !$checkbox.attr('checked'));

});

My HTML looks something like this (unfortunately it cannot change because it is being rendered with the CMS I am using):

<li>
<input id="cb1" type="checkbox">
<label for="cb1">
<div>Some Other Content</div>
<div class="pledge">Click to Pledge</div>
</label>
</li>

The jQuery.

$("div.pledge").click(function() {

  var checkboxlabel = $(this).parent("label");

  $("input[for=checkboxlabel]").attr('checked', !$checkbox.attr('checked'));

});

Using this code will toggle the checkbox if I click anywhere inside the label. What I need is for the action to only take place when I click the <div class="pledge"> element. I suspect that .stopPropagation(); will help me here but I have not been able to get it to work properly.

Here is another shot that seems to be accomplishing the same think:

$("div.pledge").click(function() {

  $("input[for=' + this.parent("label").attr("id") + ']").attr('checked', !$checkbox.attr('checked'));

});

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

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

发布评论

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

评论(5

满栀 2025-01-12 10:15:51

阅读字里行间,在我看来,以下内容无需任何 JS 即可实现您想要的结果:

<li>
<input id="cb1" type="checkbox">
<div>
<div>Some Other Content</div>
<label for="cb1">Click to Pledge</label>
</div>
</li>

http://jsfiddle .net/nnnnnn/VqmBb/

这会在复选框旁边显示“一些其他内容”和“点击承诺”,但正如您在我的演示中看到的那样,只有“点击承诺”部分选中/取消选中单击时的框。

我交换了您的标签和“pledge”div,并利用标签的 for 属性将其与复选框关联起来,以便它自动选中/取消选中它。 (尽管现在外部 div 实际上不执行任何操作,除非您需要它来进行样式设置,否则可以将其删除。)

关于您的 JS,以下行有一些问题:

$("input[for=checkboxlabel]").attr('checked', !$checkbox.attr('checked'));

首先,您的选择器 "input[for=checkboxlabel]" 似乎试图使用之前在行中声明的 checkboxlabel 变量,但您实际上所做的只是包含一个恰好包含文本“checkboxlabel”的字符串。因此,这不会选择 html 中的任何元素,因为您没有“input”元素,其“for”属性等于字符串“checkboxlabel”。此外,您还有一个未在任何地方定义的变量 $checkbox

更新:好的,以下内容应该适用于您更新的 html(它对我有用)。现有 JS 代码的问题除了您尝试使用未声明的变量 $checkbox 之外,还在于您尝试将点击处理程序绑定到“ Promise" div 意味着您尚未执行任何操作来处理标签其他部分的点击。鉴于您特别想停止点击标签的其他部分,我建议您将 .click() 处理程序附加到 标签 - 点击标签的子项将冒泡到标签的点击处理程序,这样您就可以测试被点击的元素是否是类为“pledge”的元素。如果不返回 false 来取消标签点击的默认行为,但如果它,则“pledge”元素不执行任何操作并让默认行为发生:(

$("div.pledge").parent("label").click(function(e) {
    if (!$(e.target).hasClass("pledge"))
        return false;
});

注意我是选择“div.pledge”的父级,而不是仅仅说 $("label").click() ,以便此处理不会附加到所有标签。 )

如果你不喜欢我认为 mgibsonbr 的答案是不错的选择。

Reading between the lines, it seems to me that the following will achieve your desired result without any JS:

<li>
<input id="cb1" type="checkbox">
<div>
<div>Some Other Content</div>
<label for="cb1">Click to Pledge</label>
</div>
</li>

http://jsfiddle.net/nnnnnn/VqmBb/

This displays "Some Other Content" and "Click to Pledge" next to the checkbox, but as you can see with my demo only the "Click to Pledge" part checks/unchecks the box when clicked.

I've swapped your label and the "pledge" div around, and made use of the label's for attribute to associate it with the checkbox so that it will automatically check/uncheck it. (Though now the outer div doesn't actually do anything and could be removed unless you need it for styling.)

Regarding your JS, the following line has some problems:

$("input[for=checkboxlabel]").attr('checked', !$checkbox.attr('checked'));

First, your selector "input[for=checkboxlabel]" seems to be trying to use the checkboxlabel variable declared on the line before, but what you've actually done is just include a string that happens to include the text "checkboxlabel". So that won't select any elements in your html because you have no "input" element with a "for" attribute equal to the string "checkboxlabel". Also you've got a variable $checkbox that isn't defined anywhere.

UPDATE: OK, the following should work for your updated html (it worked for me). The problem with your existing JS code, apart from the fact that you are trying to use a variable, $checkbox, that isn't declared, is that you are trying to bind your click handler to the "pledge" div which means you haven't done anything to handle clicks on other parts of the label. Given that you specifically want to stop clicks on other parts of the label I'd suggest that you attach the .click() handler to the label - clicks on the label's children will bubble up to the label's click handler, so then you can test whether the element that was clicked was the one with class "pledge". If not return false to cancel the default behaviour for a label click, but if it is the "pledge" element do nothing and let the default happen:

$("div.pledge").parent("label").click(function(e) {
    if (!$(e.target).hasClass("pledge"))
        return false;
});

(Note I'm selecting the parent of "div.pledge" rather than just saying $("label").click() so that this processing doesn't get attached to all labels.)

If you don't like that I think mgibsonbr's answer is a nice alternative.

冷清清 2025-01-12 10:15:51

如果我理解正确的话,当你说“你无法更改 HTML”时,你的意思只是服务器生成的 HTML,对吗?但是您可以使用 JavaScript 在客户端更改它吗?

jQuery(document).ready(function($) {
    $('label[for="cb1"]').removeAttr("for");
    $("div.pledge").click(function() {
        $(this).parent().prev().attr("checked", function(index,oldValue) {
            return !oldValue;
        });
    });
});

这样标签就不再有 for ,并且 div 点击是手动处理的。

If I understood correctly, when you say "you can't change the HTML", you mean only the HTML that is generated by the server, right? But can you change it in the client side, using JavaScript?

jQuery(document).ready(function($) {
    $('label[for="cb1"]').removeAttr("for");
    $("div.pledge").click(function() {
        $(this).parent().prev().attr("checked", function(index,oldValue) {
            return !oldValue;
        });
    });
});

This way the label won't have a for anymore, and the div click is handled manually.

一花一树开 2025-01-12 10:15:51

您没有以正确的方式处理此问题 - 您需要在标签中指定“for”属性并将其设置为您要分配给它的复选框的ID,如下所示:

<label for="checkbox_id">Label-text</label>
<input type="checkbox" id="checkbox_id" />

这将在您选择时选中/取消选中该复选框单击标签。 @elclanrs 上面提出的所有观点也成立,html 和 js 无效。

You're not going about this the right way - you need to specify the 'for' attribute in your label and set it to the id of the checkbox you're assigning it to like so:

<label for="checkbox_id">Label-text</label>
<input type="checkbox" id="checkbox_id" />

This will check/uncheck the checkbox when you click the label. All the points made by @elclanrs above hold too, the html and js are invalid.

葬花如无物 2025-01-12 10:15:51

您的代码(HTML 和 JavaScript)均无效。
是一个 inline 元素,内部不能有 block 元素,例如

.
然后,你的 JS 代码缺少一些 ; (我看到你添加了它们)。另外,这没有任何意义:

$("input[for=checkboxlabel]").attr('checked', !$checkbox.attr('checked'))

这应该有效。注意新的 html 标签和正确的 jQuery 代码:

html:

<li>
    <label>Something that describes this checkbox</label>
    <input id="check" type="checkbox">
    <p>Some Other Content</p>
    <a href="#" id="pledge">Click to Pledge</a>
</li>

jQ:

$('#pledge').click(function()}{ $('#check').prop('checked', true); });

Your code, both HTML and JavaScript are invalid.
<label> is an inline element which can't have block elements inside such as <div>.
Then, your JS code is missing some ; (I see you added them). Also, this makes no sense:

$("input[for=checkboxlabel]").attr('checked', !$checkbox.attr('checked'))

This should work. Notice the new html tags and the proper jQuery code:

html:

<li>
    <label>Something that describes this checkbox</label>
    <input id="check" type="checkbox">
    <p>Some Other Content</p>
    <a href="#" id="pledge">Click to Pledge</a>
</li>

jQ:

$('#pledge').click(function()}{ $('#check').prop('checked', true); });
久隐师 2025-01-12 10:15:51

将复选框移动到标签元素内。您不需要任何 js,甚至 inputlabel 元素也不需要 id 或 for 属性。试试这个。

<label>
    <input type="checkbox" />
    <div>Some Other Content</div>
    <div class="pledge">Click to Pledge</div>
</label>

演示

Move checkbox inside the label element. You don't need any js and even id or for attribute is not required for input and label element. Try this.

<label>
    <input type="checkbox" />
    <div>Some Other Content</div>
    <div class="pledge">Click to Pledge</div>
</label>

Demo

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