【问题标题】:jquery on click event inputjquery点击事件输入
【发布时间】:2013-03-28 17:58:47
【问题描述】:

想象一下:我有多个属性为“data-question-id”的 div,在这个 div 中我有一个或多个输入,可能有也可能没有属性“has-next-question”。请看下面的例子:

<div data-question-id="5">
<input type="radio" has-next-question="true" value="2"> test1
<input type="radio" value="3"> test2
</div>

<div data-question-id="6">
<input type="radio" has-next-question="true" value="5"> test3
<input type="radio" has-next-question="true" value="7"> test4
</div>

正如您在第一个 div 中看到的,我有两个输入,但一个没有 attr“has-next-question”。 我的问题是,如何在输入上绑定一个点击事件,该输入的父 div 具有 attr“data-question-id”,并且该 div 至少有一个输入具有 attr“has-next-question”。

我已经做到了:

$(document).on('click', 'div[data-question-id] input', function(e) {
          alert('click');
});

有什么帮助吗? 谢谢大家

编辑: 更改了 attr “has-next-question”,因为它的 html 属性无效。

想象一下:如果我点击“test1”它应该触发事件,但如果我点击“test2”它也应该触发,因为带有 attr“data-question-id”的父 div 至少有一个输入attr "has-next-question",对应"test1"。如果父 div 中没有带有 attr "has-next-question" 的输入,则不应触发该事件。

【问题讨论】:

  • $(document).on('click', 'div[data-question-id] input[has-next-question="true"]', function(e) { ?
  • 我知道这不是你要问的,但既然“has-next=question='true'”不是html属性,那你为什么不把它设为类名呢?触发?看起来你只在有下一个问题时才使用它,没有“错误”值。 $(document).on('click', 'div[data-question-id] input .has-next-question, function(e) { alert('click'); });

标签: javascript jquery


【解决方案1】:

你是为div 做的,所以重复一遍。

div[data-question-id] input[has-next-question]

Demo

【讨论】:

  • 也许并没有让自己清楚,想象一下:如果我点击“test1”它应该触发事件,但如果我在“test2”中触发它也应该触发,因为父 div 与 attr“ data-question-id”至少有一个输入,其属性为“has-next-question”,对应于“test1”。事件的触发必须只有在没有输入 attr "has-next-question" 时才触发
【解决方案2】:

它的 html 不正确。 has-next-question 不是有效属性。

但这应该可行,

$(document).on('click', 'div[data-question-id] input[has-next-question]', function(e) {
          alert('click');
});

编辑:(更改原始问题后),

不,您不能从中制作选择器。 jQuery 使用 CSS 选择器,它们不能从子级到父级。

但是,你可以这样做,

$(document).on('click', 'div[data-question-id] input', function(e) {
       if($(this).parent().find('[has-next-question]').length === 0 ) return;

       // Other code which needs to be executed.
});

即如果 parent 没有 [has-next-question] 属性的 child,则从函数中出来。

【讨论】:

  • 感谢有关我的无效属性的提示。请参阅我在 Ricardo Lohmann 评论中的回答。
  • 该解决方案解决了我的问题,谢谢。我会接受你的回答
【解决方案3】:

只需扩展您的选择器:

$(document).on('click', "div[data-question-id] input[has-next-question='true']", function(e) {
          alert('click');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多