Django 中的链接和按钮点击问题:所有点击都在新窗口中打开

问题描述 投票:0回答:1

自从多次提交以来,所有点击按钮、链接、提交按钮...在新窗口中打开。 提交表单不再起作用,这意味着我无法测试我所做的最后更改,并且导航显然已损坏。


发生了什么:单击任何按钮或链接都会打开一个新窗口/选项卡,因为 target="_blank" 属性将使链接行为 预期内容:单击任何按钮或链接后的操作应保留在同一页面上,因为默认的 target="self" 链接行为...


我不知道问题可能来自哪里......:

  • 不正确的
    </a>
    </button>
    闭包?我已经检查过,再检查过...
  • 卸载 tailwind 后剩下的库之一?
  • django_browser_reload 扩展出现故障?
  • 与 django-unicorn 相关的东西?

感谢您帮助我解决这个阻塞问题...

javascript django events event-handling
1个回答
0
投票

快速修复,不是永久性修复,并且不适用于表单
感谢您帮助找到永久解决方案...



<script>
/**
 * Force links to open in the same window (except those with target="_blank")
 *
 * This script prevents links without the `target="_blank"` attribute from opening in a new window/tab.
 * It achieves this by intercepting the click event and setting the current window's location to the link's URL.
 * Details:
 *     1. Selecting all anchor elements (links) using `document.querySelectorAll('a')`.
 *     2. Looping through each link and checking if it has the `target` attribute using `link.hasAttribute('target')`.
 *     3. Adding a click event listener for links without the `target` attribute.
 *     4. Inside the event listener:
 *         - `event.preventDefault()` prevents the default link behavior of opening in a new window.
 *         - `window.location.href = link.href;` sets the current window's location to the link's URL, effectively opening it in the same window.
 * 
 * @see [Stack Overflow Question](https://stackoverflow.com/questions/78510338/urgent-django-links-buttons-click-issue-all-clicks-open-in-a-new-window)
 */

const links = document.querySelectorAll('a, button');  // Select all links

let condFun = (link) => !link.hasAttribute('unicorn:click') 
                        && (!link.hasAttribute('target') || link.target != "_blank");

links.forEach(link => {
  if (condFun(link)) {          // Check if target attribute is missing
    link.addEventListener('click', (event) => {
      event.preventDefault();                  // Prevent default link behavior
      window.location.href = link.href;        // Open link in the same window
    });
  }
});        
</script>
© www.soinside.com 2019 - 2024. All rights reserved.