以下javascript代码仅在第一次单击时调用单击处理程序,并且不会重新启用该按钮:
var shareSection = $("#share");
var shortenButton = $('#shorten'); //No it is not jQuery. It is simply a predefined shortcut for querySelector
shortenButton.onclick = function() {
shortenButton.disabled = true;
if (isShortened)
{
shareSection.innerHTML = shareSection.innerHTML.replaceAll(shortened, expanded);
isShortened = false;
toggleShortenButton(shortenButton, isShortened);
shortenButton.disabled = false;
}
else
{
if (!shortened)
{
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE) {
if (request.status == 200)
{
shortened = request.responseText;
shareSection.innerHTML = shareSection.innerHTML.replaceAll(expanded, shortened);
isShortened = true;
toggleShortenButton(shortenButton, isShortened);
shortenButton.disabled = false;
}
}
};
request.open("get", window.location.href + "shorten/", true);
request.send();
}
else
{
shareSection.innerHTML = shareSection.innerHTML.replaceAll(expanded, shortened);
isShortened = true;
toggleShortenButton(shortenButton, isShortened);
shortenButton.disabled = false;
}
}
}
并且不会再次调用处理程序,因为该按钮已被禁用,即使我删除了shortenButton.disabled = true;
,它也仅在第一次单击时被调用。
渲染的html如下所示:
<section id="share">
<ul class="share">
<li><label>Share:<input type="text" value="http://easypolls.herokuapp.com/1/" readonly /></label></li>
<li><label>Embed:<input type="text" value="<iframe src="http://easypolls.herokuapp.com/1/"></iframe>" readonly /></label>
</ul>
<ul class="share">
<li><a href="https://www.facebook.com/sharer/sharer.php?u=http://easypolls.herokuapp.com/1/&t=Is%20this%20site%20great%3F" target="_blank" title="Share on Facebook"><i class="fa fa-facebook-square fa-2x" aria-hidden="true"></i><span class="sr-only">Share on Facebook</span></a></li>
<li><a href="https://twitter.com/intent/tweet?&url=http://easypolls.herokuapp.com/1/&text=Is%20this%20site%20great%3F" target="_blank" title="Tweet"><i class="fa fa-twitter-square fa-2x" aria-hidden="true"></i><span class="sr-only">Tweet</span></a></li>
<li><a href="https://plus.google.com/share?url=http://easypolls.herokuapp.com/1/" target="_blank" title="Share on Google+"><i class="fa fa-google-plus-square fa-2x" aria-hidden="true"></i><span class="sr-only">Share on Google+</span></a></li>
</ul>
<input type="button" id="shorten" value="Shorten links" />
</section>