我正在使用jQuery单击事件处理程序将点击事件添加到存在于我的HTML中的所有锚标记。 但点击事件只能使用一次。基本上onclick行动,我显示一个弹出窗口,它只显示一次。如果我再次点击它不显示。jQuery:为什么点击事件只能工作一次?
下面是我的代码:
function onClickLoginPopup (anchor)
{
var url = anchor.href;
var head = document.getElementsByTagName('head')[0];
var mainPopup = $('#popupMain');
if (mainPopup.length == 0 && mainPopup.is(":visible") == false)
{
// load popup.css
var styleSheet = document.createElement('link');
styleSheet.href = 'http://192.168.1.6:8080/OtherDomain/css/mpw.css?' + new Date();
styleSheet.rel = "stylesheet";
head.appendChild(styleSheet);
$.ajax({
url: "http://192.168.1.6:8080/OtherDomain/popup.html",
data: '',
cache: false,
success: function(data){
document.body.innerHTML += data;
if($('#popupMain').length > 0) {
alert('ShowPopup');
showPopup();
}
}
});
}
}
function addClickEventListenerToAllAnchorTag()
{
var anchors = document.getElementsByTagName("a");
for(var i = 0; i < anchors.length; i++)
{
var anchor = anchors[i];
//console.log(anchor);
anchors[i].addEventListener("click",function(event)
{
console.log(this.href + ' clicked');
onClickLoginPopup(anchor);
}, false);
}
}
function initialize(){
var head = document.getElementsByTagName('head')[0];
var host = "192.168.1.6";
var server = "http://" + host + ":8080/OtherDomain/";
var req = document.createElement("script");
req.src = server + "js/jquery.js?" + new Date();
req.type = "text/javascript";
head.appendChild(req);
// load Popup.js
var popupJs = document.createElement("script");
popupJs.type = 'text/javascript';
popupJs.src = "http://192.168.1.6:8080/OtherDomain/js/Popup.js?" + new Date();
head.appendChild(popupJs);
addClickEventListenerToAllAnchorTag();
}
window.onload = initialize;
这里上的window.onload我打电话初始化基本上我加载脚本弹出和jQuery功能,并呼吁这是刚刚获取所有锚标签从addClickEventListenerToAllAnchorTag()函数HTML并添加click事件监听器。里面,我打电话onClickLoginPopup()函数是ajax调用来获取远程元素。有在showPopup()调用mehtod下面的代码:
Popup.js
function showPopup() {
console.log('In showPopup');
//$('#popupMain').show();
document.getElementById('popupMain').style.display = 'block';
}
但不知何故,这个弹出是越来越显示只有一次,未能显示在随后的点击。 请帮忙。
当你第二次点击它时'mainPopup.is(“:visible”)'的值是多少? – mininoz 2015-04-06 08:42:24
DOM和jQuery的可怕组合。另外我怀疑你需要添加preventDefault到主播 – mplungjan 2015-04-06 08:46:58
@mininoz第二次函数不会被调用 – mahendrakawde 2015-04-06 08:49:01