You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EJS文件中EventListener click失效问题排查与修复求助

Fixing the Click Event Listener Issue for Map Restaurant Lookup

Hey there! Let's walk through why your click event isn't firing properly and fix it step by step.

1. Fix the abs() Reference Error

First off, JavaScript doesn't have a global abs() function—you need to use Math.abs() instead. Using plain abs() will throw a ReferenceError, which stops your getClickPosition function from running entirely. That's probably the biggest reason your click handler isn't working.

2. Correct the Coordinate Comparison Logic

You have two small but critical mistakes in your condition check:

  • You're comparing the click's y-position to the restaurant's x-coordinate (restaurants[i][1][0] instead of restaurants[i][1][1])
  • The parentheses around the y-position calculation are misplaced, which breaks the comparison logic entirely

3. Fix Unclosed HTML Tag (Hidden DOM Issue)

In your myinfo.ejs, the <img> tag isn't closed properly. This can mess up the DOM structure, which might indirectly affect element selection or event propagation down the line.

4. Add DOM Load Safety (Optional but Reliable)

Even though your console.log shows the .map element is found, wrapping your event binding in a DOMContentLoaded listener ensures it runs only after all elements are fully rendered. This prevents edge cases where the element might not exist yet when the script runs.

Updated Code Examples

Fixed click.js:

// Wait for the entire DOM to load before binding events
document.addEventListener('DOMContentLoaded', function() {
  let clickArea = document.querySelector('.map');
  let rtname = document.querySelector('.rt');

  clickArea.addEventListener("click", getClickPosition, false);

  function getClickPosition(e) {
    var xpos = e.clientX;
    var ypos = e.clientY;
    console.log(xpos + " " + ypos);

    var restaurants = [["chicken", [500, 600]]];
    for (var i = 0; i < restaurants.length; i++) {
      // Use Math.abs() and correct coordinate indices/parentheses
      if (Math.abs(xpos - restaurants[i][1][0]) < 5 && Math.abs(ypos - restaurants[i][1][1]) < 5) {
        rtname.innerHTML = restaurants[i][0];
      }
    }
  }
});

Fixed myinfo.ejs Image Tag:

Change this broken line:

<img class="photo1" src="../images/profile/<%= session.image%>

To the properly closed version:

<img class="photo1" src="../images/profile/<%= session.image%>">

Quick Tip

Always check your browser's DevTools Console (F12) for errors when events aren't firing—this is the fastest way to catch syntax or reference issues like the abs() mistake!

内容的提问来源于stack exchange,提问作者Newbie Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:00:08