event.target.parentNode ...指向Chrome和Firefox中的不同父级? [英] event.target.parentNode... pointing to different parents in chrome and firefox?

查看:638
本文介绍了event.target.parentNode ...指向Chrome和Firefox中的不同父级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个项目中,我有一个按钮,其中包含用于图像样式的按钮...我正在尝试实现功能,以便在单击按钮时使用event.target.parentNode.parentNode ...多次从最顶层的父div处获取HTML5数据属性(postid),在Firefox中,我需要调用4次parentNode,但在Chrome中却无法正常工作,我需要调用5次parentNode,这意味着两次浏览器指的是不同的父母.我添加了$(event.target).parent().parent().css('border','5px solid black');找出每个浏览器正在考虑的目标.我发现Chrome认为event.target是图像(实际上是被单击的图像),但是Firefox认为按钮是event.target(实际上是事件的附加位置).....此按钮及其事件代码可在两个浏览器上移植,而无需删除按钮标签(有效)内的图像.

In this project am working on I have button that has and image inside it for styling purposes... I am trying to implement the functionality such that when the button is clicked I use event.target.parentNode.parentNode... a number of times to get an HTML5 data attribute(postid) from one the topmost parent divs, in Firefox I need to call parentNode 4 times and it works in Chrome it does not work I need to call parentNode 5 times, this means the two browsers are referring to different parents. I added $(event.target).parent().parent().css('border','5px solid black'); to find out which target each browser is considering. I found Chrome considers the event.target to be the image(which is what is actually clicked) but Firefox considers the button to be the event.target(which is where the event was actually attached)..... How can I make this button and its event code portable on both browsers without removing the image inside the button tag(that worked).

代码看起来像

$(document).on('click', '.opinion', function(event) {

  try {
    post_id =  event.target.parentNode.parentNode.parentNode.parentNode.dataset['postid'];
    //$(event.target).parent().parent().css('border','5px solid black');
    url = $('#opinionUrl' + post_id).val();
    token = $('#token').val();
  } catch (e) {

    alert(e);
  }
///Some more code to do stuff
});

<button class="icon opinion">
  <img class="icon" src="{{URL::asset('assets/icons/haha.png')}}">
</button>

推荐答案

为什么使用jQuery并链接parentNode.parent()?

Why use jQuery and chain parentNode or .parent()?

.closest()将为您完成任务 https://api.jquery.com/closest/

post_id = $(this).closest("[data-postid]").data().postid;

这篇关于event.target.parentNode ...指向Chrome和Firefox中的不同父级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆