简体   繁体   English

使用 on JQuery 事件获取单击的子元素文本

[英]Get clicked children element text with the on JQuery event

I saw some questions who were similar to mine and even one that is pretty much identical And the answer to that question was to use $(this) for some reason when I use this it executes the $(this) on the document .我看到了一些与我的问题相似的问题,甚至是一个几乎相同的问题。这个问题的答案是使用$(this)出于某种原因,当我使用 this 时,它会在document上执行$(this)

var $dropDownItems = $('.notifi-drop').children();
$(document).on('click', $dropDownItems, function(event){

this is the code I am trying to execute.这是我要执行的代码。 If I do a normal .click() event it works fine and I can use this to get the corrent element.如果我执行正常的.click()事件,它可以正常工作,我可以使用this来获取正确的元素。 eg例如

$($dropDownItems).click('click', function(event){

I tried the following (with the on event) but all of them were undefined我尝试了以下(使用on事件),但所有这些都undefined

console.log($(this).attr('id'))
console.log($(event.target.text))
console.log($(this).text())
    

Just a note: If you didn't see, $dropDownItems is the children of a specific element.请注意:如果您没有看到, $dropDownItems是特定元素的子元素。 I guess that this is the problem in here.我想这就是这里的问题。

The class and the children of the class: class 和 class 的子代:

<div class="dropdown-menu notifi-drop dropdown-menu-right">
                                {% for i in notifications %}
                                    <a class="dropdown-item friend-name-{{username}}">{{i}}</a>
                                    <button type="button" class="btn btn-outline-danger friend-rejected">Reject</button>
                                    <a>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀</a>
                                    <button type="button" class="btn btn-outline-success friend-accepted">Accept</button>
                                    <hr>
                                {% endfor %}
                            </div>

To clarify even more, I want to detect which child was clicked on and get the child's text.(what I am doing with the click even and this ).为了进一步澄清,我想检测点击了哪个孩子并获取孩子的文本。(我正在用 click even 和this做什么)。

FYI: The reason I want to use the on event is because I am appending data and the click event can't handle it.仅供参考:我想使用on事件的原因是因为我正在附加数据,而 click 事件无法处理它。

When you want to use event delegation, you should be using a selector, not a jQuery object.当您想使用事件委托时,您应该使用选择器,而不是 jQuery object。

So in your case you want to use > * to match the children of the element.因此,在您的情况下,您想使用> *来匹配元素的子元素。

$(document).on('click', '.notifi-drop > *', function(event){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM