我在Web用户控件上有一些javascript,并在页面上实例化该控件的两个实例。控件只是显示一些帮助文本,应切换为打开或关闭。
document.ready函数按预期运行,因为它运行了两次。但是当我点击任一控件时,脚本会运行两次,因此控件会打开然后关闭。
如何确保脚本仅针对单击的控件运行一次。
<div class="helpControlHolder">
<div class="expandableHeading">Show (Hide) </div>
<div class="expandableContent commentsTable" >
<ul id="ulComments" runat="server"></ul>
</div>
</div>
<script type="text/javascript">
function slideToggle(e, ui) {
debugger;
//find the right control to slideToggle
var ct = e.currentTarget;
var controlHolder = ct.parentNode; //up the dom one element
$(controlHolder).find(".expandableContent").slideToggle(500); //back down the dom to the element we want to animate
}
$(document).ready(function () {
//find the right control to hide
var pare = $('.helpControlHolder');
pare.find(".expandableContent").hide();
pare.find(".expandableHeading").click(function (e, ui) {
e.preventDefault();
slideToggle(e, ui);
});
});
</script>
答案 0 :(得分:0)
Try to change your javascript as follows:
<script type="text/javascript">
function slideToggle(e, ui) {
debugger;
//find the right control to slideToggle
var ct = e.currentTarget;
var controlHolder = ct.parentNode; //up the dom one element
$(controlHolder).find(".expandableContent").slideToggle(500); //back down the dom to the element we want to animate
}
$(document).ready(function () {
//find the right control to hide
var pare = $('.helpControlHolder');
pare.find(".expandableContent").hide();
});
$(function(){
$(".expandableHeading").click(function (e, ui) {
e.preventDefault();
slideToggle(e, ui);
});
});
</script>
Hope it helps.
答案 1 :(得分:0)
问题是(正如@UmairP所指出的)脚本被添加到页面两次。我将脚本移动到一个单独的文件(helpControl.js),然后将以下条目添加到我正在使用的母版页的“站点脚本”部分:
<%--Site Scripts--%>
<asp:ScriptReference Path="~/Scripts/C/helpControl.js" />
这意味着它只会被添加一次并按预期运行。
感谢您的回复