在下面的代码中,当我点击“投票”时,会显示投票结果屏幕,但当我点击“返回投票”时,投票会重新显示,但“显示选项”按钮不再可见。有没有一种方法可以防止在单击“返回投票”时隐藏此按钮。
这是 fiddle :http://jsfiddle.net/E2gku/2/
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/5968383.js"></script>
<noscript><a href="http://polldaddy.com/poll/5968383/">This is a test question ?</a></noscript>
<style>
.pds-pd-link {
display: none !important;
}
.pds-box {
width: 200px !important;
}
.pds-input-label{
width: auto! important;
}
.PDS_Poll{
margin-bottom:15px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('.pds-question').append('<input type="button" class="showanswer" value="Show Options"/>');
$('.pds-vote').css('display' , 'none');
$('.pds-answer').css('display' , 'none');
$('.pds-vote-button').css('display' , 'none');
$('.pds-view-results').css('display' , 'none');
$('.showanswer').on('click', function () {
$('.pds-vote').show();
$('.pds-answer').show();
$('.pds-vote-button').show();
$('.pds-view-results').show();
$('.showanswer').hide();
$('.pds-question').append('<input type="button" class="hideanswer" value="Hide Options"/>');
$('.hideanswer').on('click', function () {
$('.pds-vote').hide();
$('.pds-answer').hide();
$('.pds-vote-button').hide();
$('.pds-view-results').hide();
$('.showanswer').show();
$('.hideanswer').hide();
});
});
});
</script>
最佳答案
您可以使用事件委托(delegate)在用户单击返回问题时重新附加按钮:
$('body').on('click', '.pds-return-poll', function() {
setTimeout(function(){
$('.pds-question').append('<input type="button" class="showhideanswer" value="Hide Options"/>');
}, 10);
});
我也干掉了你的代码,只是一点点:
$(document).ready(function() {
$('.pds-answer, .pds-vote').css('display' , 'none');
$('.pds-question').append('<input type="button" class="showhideanswer" value="Show Options"/>');
$('body').on('click', '.pds-return-poll', function() {
setTimeout(function(){
$('.pds-question').append('<input type="button" class="showhideanswer" value="Hide Options"/>');
}, 10);
}).on('click', '.showhideanswer', function() {
$('.pds-answer, .pds-vote').toggle();
if (this.value == 'Show Options')
$(this).val('Hide Options');
else
$(this).val('Show Options');
});
});
JSFiddle .
超时是因为你的默认函数优先,所以将这个超时解释为一个延迟对象。
显然,由于按钮是动态添加的,因此它也需要像我上面的代码中那样进行事件委托(delegate)(或者重新绑定(bind)事件处理程序,由您选择)。
编辑:修复了 Firefox 中的错误。
edit2:再干一点。选择器现在只被使用一次,所以我放弃了选择器缓存,因为 $(document).ready
的选择器不能在 showhideanswer
中重复使用s click
处理程序,因为出于某种原因,您的插件开发人员决定在您转到结果页面并返回投票页面时创建新元素,而不是重新使用相同的元素。
关于javascript - 防止按钮永久消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11301035/