如何在ASP:Repeater中点击Div获取内部<p>值并拼接至URL
解决ASP:Repeater点击游戏盒子跳转带标题URL的问题
我来帮你搞定这个需求,核心就是让点击事件能精准关联当前的游戏盒子,提取对应标题后拼接成目标URL就行,具体步骤如下:
1. 修改Repeater的点击事件绑定
首先要把当前点击的div对象传递给点击函数,因为Repeater会生成多个结构相同的游戏盒子,必须明确是哪一个被点击了。修改你的Repeater ItemTemplate里的div代码:
<asp:Repeater runat="server" ID="discountRepeater1"> <ItemTemplate> <!-- 修改onclick事件,传入当前div对象this --> <div class="div_discount_contentbox" onmouseover="this.style.backgroundColor='#35373A'" onmouseout="this.style.backgroundColor='#1B1C1E'" onclick="onClickDivDiscount1(this)" runat="server"> <div class="div_wrap_discount_image"> <img src='<%# Eval("메인이미지") %>' class="discount_image" id="discount_image" runat="server" /> </div> <div class="div_discount_title"> <p class="p p_discount_title"><%# Eval("게임명") %></p> </div> <div class="div_discount_price"> <div class="div_wrap_discount_rate"> <img src="Images/Icon/Icon_Discount.png" class="icon_discount" /> <p class="p p_discount_rate"><%# Convert.ToDouble(Eval("할인율")) * 100 %>%</p> </div> <div class="div_wrap_discount_price2"> <p class="p p_discount_price"><strike>₩<%# Eval("게임가격") %>원</strike></p> <br /> <p class="p p_discounted_price" id="p_price" runat="server"> ₩<%# Convert.ToInt32(Eval("게임가격")) - Convert.ToInt32(Eval("게임가격")) * Convert.ToDouble(Eval("할인율")) %>원 </p> </div> </div> </div> </ItemTemplate> </asp:Repeater>
2. 编写JavaScript点击处理函数
在页面的<script>标签里添加以下函数,实现标题提取和URL跳转:
function onClickDivDiscount1(clickedDiv) { // 从当前点击的盒子里获取游戏标题文本 const gameTitle = clickedDiv.querySelector('.p_discount_title').textContent.trim(); // 拼接目标URL,用encodeURIComponent处理标题中的特殊字符/空格 const baseUrl = window.location.pathname; // 动态获取当前页面路径,避免硬编码 const newUrl = `${baseUrl}/GameTitles/${encodeURIComponent(gameTitle)}`; // 跳转到新URL window.location.href = newUrl; // 如果想要无刷新修改URL(需要后端支持路由规则),可以替换成下面这行: // history.pushState({}, '', newUrl); }
代码说明:
clickedDiv.querySelector('.p_discount_title'):精准定位当前点击盒子内的标题标签,不会和其他游戏盒子的标题混淆encodeURIComponent(gameTitle):对标题进行URL编码,处理空格、特殊字符(比如冒号、书名号),避免URL失效window.location.pathname:动态获取当前页面路径,比硬写Store_Main.aspx更灵活,页面路径变化时无需修改代码
小优化建议
你的Repeater里给每个游戏盒子设置了固定id div_discount_contentbox1,这会导致页面生成多个重复id(HTML规范要求id唯一)。如果不需要后端操作这个div,建议去掉id="div_discount_contentbox1"和runat="server";如果必须保留后端操作,可以用Eval生成唯一id,比如:
id='<%# "div_discount_contentbox_" + Eval("게임명") %>'
内容的提问来源于stack exchange,提问作者몽까찌
相关产品推荐
相关产品推荐

