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

如何利用复选框获取输入框值并生成指定格式的URL链接?

问题解决方案:通过复选框触发生成指定格式的用户链接

核心需求

当用户在id="profile"的文本框填写用户名,且勾选id="gallery"的复选框时,生成两个符合要求的链接:

  • Profile链接使用原输入的用户名
  • Gallery链接使用转为小写的用户名

修正后的完整代码

HTML 代码

<script src="https://videochatencasa.com/buton/jquery-3.4.0.min.js"></script>

<input type="text" placeholder="your username" id="profile" required>
<br>
<input type="checkbox" id="gallery" name="chatprof2">
<!-- 用于展示生成的链接的容器 -->
<div id="links-container"></div>

JavaScript 代码

// 监听复选框的状态变化
$('#gallery').on('change', function() {
  const linksContainer = $('#links-container');
  // 清空之前生成的链接
  linksContainer.empty();
  
  // 仅当复选框被勾选且文本框不为空时生成链接
  if ($(this).is(':checked')) {
    const nickname = $('#profile').val().trim();
    if (nickname) {
      // 生成Profile链接
      const profileLink = `<a href='https://web.com/profile/${nickname}'>Profile</a>`;
      // 生成Gallery链接,用户名转为小写
      const galleryLink = `<a href='https://web.com/profile/gallery/${nickname.toLowerCase()}'>Gallery</a>`;
      // 插入到容器中,可根据需求调整排版
      linksContainer.append(`${profileLink}<br>${galleryLink}`);
    }
  }
});

关键说明

  1. 事件监听:通过change事件监听复选框的勾选/取消状态,确保状态变化时触发逻辑
  2. 值的获取与校验:先获取文本框的值并去除首尾空格,避免空值或无效输入
  3. 用户名大小写处理:使用toLowerCase()方法将用户名转为小写,满足Gallery链接的格式要求
  4. 链接容器:新增links-container用于存放生成的链接,避免页面内容混乱

验证预期结果

当用户在文本框输入HANNA并勾选复选框时,页面会生成以下内容:

<a href='https://web.com/profile/HANNA'>Profile</a>
<br>
<a href='https://web.com/profile/gallery/hanna'>Gallery</a>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:32:52