【问题标题】:event.preventDefault(), event.stopPropagation() is not working to stop redirection of pages while clicking on anchor tagevent.preventDefault(), event.stopPropagation() 在单击锚标记时无法停止页面重定向
【发布时间】:2023-03-20 08:30:01
【问题描述】:

我正在开发一个应用程序(在 React 中),其中来自不同站点的网页加载到 iframe 中(将页面下载到本地系统)。 用户必须单击页面,我将为单击的元素生成 xpath 或 cssPath。 为了检测点击,我添加了 eventListeners。

问题陈述: 我也能够识别元素和 CSS 路径/Xpath。但是,如果元素是具有 href 属性值的锚标记。在生成路径的同时,它还试图导航到在锚标记的 href 属性中添加的页面。

试过了:

  • event.preventDefault()
  • event.stopPropagation()
  • event.stopImmediatePropagation()
  • 添加点击监听,监听附加方法返回false(我的代码在mouseUpListener附加函数中)

示例代码:

<iframe  src={iframeSrc} sandbox="allow-same-origin allow-scripts" ref='htmlPageRef'/>

HTML 页面包含:

<a href='visitMySite.com'> Go to My Website</a>

添加监听器:

 frameDoc.addEventListener("mouseup", this.mouseupListener, false);

在事件监听器的附加方法中,我执行了event.preventDefaultevent.stopPropagationevent.stopImmediatePropagation

import React from 'react';
import ReactDOM from 'react-dom';
import Reminder from './reminder';

class TodoCheckList extends  React.Component{
    componentDidMount(){
        console.log('testest');
    }

    callMe(that){
         console.log('test');
        let iframe = ReactDOM.findDOMNode(that.refs.htmlPageRef);
        console.log(iframe);
        var frameDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
        frameDoc.addEventListener("click", this.clickListener, false);
     }


    clickListener = (e)=> {
        console.log(e);
        e.preventDefault();
    }
    render(){
        return (
        <div >

            <iframe onClick={ () => this.callMe(this) } ref='htmlPageRef' src="frameFILE.html" sandbox="allow-same-origin allow-scripts" width="600"></iframe>
        </div>
        );
    }
}
export default TodoCheckList;

iframe 框架文件内容:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
        Iframe page
        <a href="google.co.in">Open Google</a>

</body>
</html>

【问题讨论】:

  • 在点击链接时同步使用preventDefault肯定会阻止浏览器的默认跟随链接行为。所以 else 正在发生,但问题中的代码和信息太零碎,无法说明是什么。请使用 minimal reproducible example 来更新您的问题,以展示问题,最好是使用 Stack Snippets([&lt;&gt;] 工具栏按钮)的 runnable 问题。 Stack Snippets 支持 React,包括 JSX; here's how to do one.

标签: javascript jquery addeventlistener preventdefault stoppropagation


【解决方案1】:

mouseup 更改为click 并添加return false;

document.getElementById('myLink').addEventListener("click", function(event) {
  event.preventDefault();
  event.stopPropagation();
  event.stopImmediatePropagation();
  return false;
}, false)
&lt;a href='visitMySite.com' id='myLink'&gt; Go to My Website&lt;/a&gt;

【讨论】:

  • 我也检查了那个用例。这不是工作。
  • 更新了一个示例代码sn-p,目标是停止锚标签的重定向
猜你喜欢
  • 2023-04-10
  • 2013-07-18
  • 2018-04-22
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
相关资源
最近更新 更多