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

如何用JavaScript实现选中城市后更新位置信息并移除其他选项

解决点击选中城市后替换页面内容的问题

你的代码存在几个关键问题,直接修正如下:

1. 补充可选城市的HTML结构

当前页面只有默认位置占位符,没有可选择的城市列表,需要在data-location-container中添加可选城市项,通过数据属性存储城市/国家值:

</div>
      <div class="locations" data-location-container>
        <!-- 默认显示的位置 -->
        <div class="mainPlace" id="userLocation">
          <div class="city">City<span>,</span></div>
          <div class="country">Co</div>
        </div>
        <!-- 新增可选城市列表 -->
        <div class="location-options">
          <div class="location-option" data-city="Beijing" data-country="CN">Beijing, CN</div>
          <div class="location-option" data-city="Shanghai" data-country="CN">Shanghai, CN</div>
          <div class="location-option" data-city="New York" data-country="US">New York, US</div>
        </div>
      </div>
    </div>
  </header>

  <template id="location-template" data-location>
    <div class="mainPlace-template">
      <div class="city" data-city></div><span>,</span>
      <div class="country" data-country></div>
    </div>
  </template>

2. 修正JavaScript代码错误

  • 事件回调参数是事件对象,需从点击元素提取数据
  • 移除未定义的selectedLocation,直接操作容器元素
  • 增加判断,仅在点击城市选项时触发逻辑:
const userLocationContainer = document.querySelector("[data-location-container]")
const locationTemplate = document.getElementById("location-template");

function setValue(selector, value, { parent = document } = {}) {
    const element = parent.querySelector(`[data-${selector}]`);
    if (element) element.textContent = value;
}

userLocationContainer.addEventListener('click', handleLocation);

function handleLocation(event) {
    // 仅响应城市选项的点击
    const targetOption = event.target.closest('.location-option');
    if (!targetOption) return;

    // 从点击元素获取城市和国家数据
    const city = targetOption.dataset.city;
    const country = targetOption.dataset.country;

    const clonedTemplate = locationTemplate.content.cloneNode(true);
    setValue("city", city, { parent: clonedTemplate });
    setValue("country", country, { parent: clonedTemplate });

    // 清空容器并插入选中的模板内容
    userLocationContainer.innerHTML = '';
    userLocationContainer.append(...clonedTemplate.childNodes);
}

3. 可选:统一逗号显示结构

如果希望和原结构一致,把逗号放在.city元素内部,可修改模板:

<template id="location-template" data-location>
  <div class="mainPlace-template">
    <div class="city" data-city><span>,</span></div>
    <div class="country" data-country></div>
  </div>
</template>

功能说明

点击任意城市选项后,容器会清空所有原有内容,仅展示选中的城市和国家信息;通过closest('.location-option')避免误触容器空白区域触发逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 20:52:45