简体   繁体   English

Javascript onclick停止工作,多个动态创建的div

[英]Javascript onclick stops working, multiple dynamically created divs

I have run into a strange problem, i am creating a lot of dynamically divs. 我遇到了一个奇怪的问题,我正在创建很多动态div。 And i recently found out that some of my divs doesn't fire the onclick event? 我最近发现我的某些div不会触发onclick事件? All the divs are created using the same template, so why are some not working? 所有div都是使用相同的模板创建的,那么为什么有些不起作用? Most of the time, its the 4-5 from the bottom. 大多数情况下,它是从底部开始的4-5。 If you click on one of the others and then try again, you might get one of those to trigger. 如果单击其他之一,然后重试,则可能会触发其中之一。 But only sporadically. 但是只是零星的。

Code to create the divs: 创建div的代码:

// Code to loop thru the number of players and create the divs accordingly
for (fieldNumber = 0; fieldNumber < 18; fieldNumber++) {
        var holderDiv = CreateDiv('gameCellLarge', '');
        holderDiv.style.width = 150 + extraCellWidth + 'px'; // Ändra storleken beroende på antalet spelare

        if (fieldNumber == 0 || fieldNumber == 6 || fieldNumber == 8 || fieldNumber == 17)
            newField = CreateDiv('gameCellMedium borderFull gameText', gameText[fieldNumber]);
        else
            newField = CreateDiv('gameCellMedium borderWithoutTop gameText', gameText[fieldNumber]);
        holderDiv.appendChild(newField);

        for (playerNumber = 0; playerNumber < players.length; playerNumber++) {            
            holderDiv.appendChild(players[playerNumber].InitField(fieldNumber));
        }
        gameFieldDiv.appendChild(holderDiv);
    }




GameField.prototype.InitField = function(fieldNumber) {
var newField = document.createElement("div");
if (fieldNumber == 0 || fieldNumber == 6 || fieldNumber == 8 || fieldNumber == 17)
    newField.className = 'gameCellSmall borderFull gameText gameTextAlign';
else
    newField.className = 'gameCellSmall borderWithoutTop gameText gameTextAlign';

var instance = this;
if (fieldNumber == 6 || fieldNumber == 7 || fieldNumber == 17) { }
else
    newField.onclick = function() { instance.DivClick(fieldNumber); return false; }

this.fields[fieldNumber] = newField;
this.score[fieldNumber] = 0;
return newField;
}

I added the return false to the click function, but it still behaves strangely. 我将return false添加到click函数中,但是它的行为仍然很奇怪。 Why are some not triggering? 为什么有些不触发? I create around 18 divs / player. 我创建约18个div /播放器。 But it happens even if i just create one player. 但是即使我只创建一个播放器,也会发生这种情况。

Do i perhaps need to cancel the event once i am done with it? 完成活动后,是否可能需要取消活动? (Like the return false; is trying to do) Works sometimes but not always... (就像返回false一样;正在尝试这样做)有时但并非总是可行...

I have run out of ideas, here is a link to the script. 我的想法用光了,这里是脚本的链接。 Maybe i have just missed something. 也许我只是错过了一些东西。 The script I have changed it a bit, so just press the button and click on the lower end of the game field (yatzy, kåk etc). 我对脚本进行了一些更改,因此只需按一下按钮,然后单击游戏字段的下端(yatzy,kåk等)即可。 It should popup alerts when clicked. 单击时应弹出警报。 Sometimes they work sometimes they don't. 有时他们工作有时不工作。

Your code appears to be fine, it looks like the CSS is messing things up. 您的代码看起来不错,看起来CSS搞砸了。

The problem is that the 'gameCellLarge' divs are getting out of phase with the 'gameCellMedium' and 'gameCellSmall' divs that they enclose. 问题在于'gameCellLarge'div与它们所包围的'gameCellMedium'和'gameCellSmall'div异相。 This is because they have a 'position:relative;' 这是因为它们具有“ position:relative;” style attribute which allows them to wander from where they should be. 样式属性,使他们可以从应有的位置徘徊。 (You can visually see what's happening by using the debugger that comes with most browsers, eg Firebug with Firefox, or the Developer Tools with Chrome.) (通过使用大多数浏览器附带的调试器,您可以直观地看到正在发生的情况,例如Firefox的Firebug或Chrome的开发人员工具。)

Only the portion of a 'gameCellSmall' box that overlaps with its enclosing 'gameCellLarge' box is clickable. 只能单击“ gameCellSmall”框与其封闭的“ gameCellLarge”框重叠的部分。 You'll find that all the boxes have a clickable region, but that the region shrinks as you get to the bottom of the table. 您会发现所有框都有一个可单击的区域,但是当您到达表格底部时,该区域会缩小。 That's because the large cells get more and more out of phase with the small cells as you go down the table. 这是因为当您下桌时,大型单元格与小型单元格越来越异相。 But if you click toward the top of a box it will work, although if you don't realize this it will seem that the response is random and sporadic. 但是,如果您单击框顶部,它将起作用,尽管如果您没有意识到这一点,则似乎响应是随机的和零星的。

Anyways, you can fix this problem by removing 'position:relative' from the .gameCellLarge style. 无论如何,您可以通过从.gameCellLarge样式中删除'position:relative'来解决此问题。 This doesn't seem to make a difference to the layout, so it should be OK to do this. 这似乎对布局没有影响,所以应该可以做到这一点。 You could also specify 'border:1px solid black;' 您还可以指定“ border:1px纯黑色;” in the .gameCellLarge style. 在.gameCellLarge样式中。

Hope this helps. 希望这可以帮助。

Well, first of all, I'm going to assume that the ones that are not working are NOT being created with a fieldNumber of 6, 7, or 17. 好吧,首先,我将假定未使用fieldNumber 6、7或17创建的那些无效的对象。

That aside... If the problem happens to be in stopping event propagation, you might try something like the following: 除此之外...如果问题恰巧在于停止事件传播,则可以尝试以下操作:

newField.onclick = function(e) {
     if (!e) var e = window.event;
     instance.DivClick(fieldNumber);
     if (e.preventDefault) e.preventDefault();
     else e.returnValue=false;
     return false;
}

Other than that, I can't really test anything to figure out the issue. 除此之外,我真的无法进行任何测试来找出问题所在。

This is not a direct answer to your problem, but a situation like this is a good candidate for event delegation. 这不是直接解决您的问题的方法,但是这种情况很适合进行事件委派。 Just google for it and you will find plenty of sources. 只是谷歌它,你会发现很多资源。 Here is a good one - http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/ 这是一个很好的网站-http: //www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/

The way it works is by attaching an event handler to the parent container and catch the events that bubble up. 它的工作方式是将事件处理程序附加到父容器并捕获冒泡的事件。 You can then obtain the source of the event ( event.srcElement in IE and event.target in firefox) and do stuff based on it. 然后,您可以获取事件的源(IE中的event.srcElement和firefox中的event.target )并基于该事件进行处理。 In your case, if you attach an unique id to each of your clickable divs, you can check against it and call the appropriate event handler. 就您而言,如果您为每个可点击的div附加一个唯一的ID,则可以对其进行检查并调用相应的事件处理程序。

It is a much more cleaner way of doing things rather than attaching many event handlers. 与附加许多事件处理程序相比,这是一种更清洁的处理方式。

[Edit] : Found your problem. [编辑] :找到您的问题。 Basically, your gamecellLarge divs have no heights because they contain only floated elements. 基本上,您的gamecellLarge div没有高度,因为它们仅包含浮动元素。 You have tried to remediate that by adding height: 30px but that causes the div to overlap the next set of divs. 您尝试过通过添加height: 30px来进行补救,但这会使div与下一组div重叠。 If you have Firebug, highlight the elements and see the problem. 如果您有Firebug,请突出显示元素并查看问题。 You click always works if you click the top 1/3rd of the box. 如果单击框的顶部1/3,则单击始终有效。

Change the style to something like this and it should work. 将样式更改为这样,它应该可以工作。

.gameCellLarge {
    clear: both;
    overflow: hidden;
    width: 200px;
    zoom: 1
}

At least three of them are not triggering any events, because they have no onClick handler: 其中至少三个没有触发任何事件,因为它们没有onClick处理程序:

if (fieldNumber == 6 || fieldNumber == 7 || fieldNumber == 17) { }

I'm not sure that that's what you're talking about, though, if you say that the bottom 4 or 5 divs do nothing. 但是,如果您说最下面的4或5个div没有任何作用,那么我不确定这就是您在说的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM