我是一个有经验的程序员,但对网络编程有点陌生。我正在试图学习Javascript,HTML5和SVG使用VS2010编写一个HTML页面,发挥Tic-Tac-脚趾与Javascript。
我正在成功地将九个方块中的每一个创建为SVG <rect...>
元素,但是我在每个方块的单击事件处理程序上遇到了问题。
下面是HTML文件中存在的基本SVG元素:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
id="svgTTT" width="150" height="150" viewBox="0 0 300 300" >
<rect width="3" height="300" x="99" fill="#008d46" />
<rect width="3" height="300" x="199" fill="#000000" />
<rect width="300" height="3" y="99" fill="#008d46" />
<rect width="300" height="3" y="199" fill="#d2232c" />
</svg>
这些静态<rect>
元素绘制TicTacToe板的交叉散列行。九个板方块是在从windows事件调用的javascript函数中创建的(如下所示)。
下面是javascript (在HTML中的<script>
元素中是行内的):
<script type="text/javascript">
function getEl(s) { return document.getElementById(s); }
var svg; // get the TTT svg
// execute after HTML has rendered
window.onload = function () {
svg = getEl("svgTTT");
tttSetupSquares(svg);
alert("click-squares are setup.");
}
var cells = new Array(3);
// setup the click squares
function tttSetupSquares(brd) {
for (var i = 0; i < 3; i++) {
cells[i] = new Array(3);
for (var j = 0; j < 3; j++) {
var x = 3 + (i * 100);
var y = 3 + (j * 100);
var newId = "svgTTTsqr" + i.toString() + j.toString();
// add in new rect with html
brd.innerHTML += "<rect id='"+newId+"' width='93' height='93' "
+ "fill='#00DD00' x='" + x.toString() + "' y ='" + y.toString() + "'"
+ " />";
//find it using the newId
var rect = document.getElementById(newId);
//make a cell object to contain all of this
var cell = {
col: i,
row: j,
pSvg: svg,
rect: rect,
handleClick: function (event) {
try {
// this line fails because `this` is the target, not the cell
var svgNS = this.pSvg.namespaceURI;
var line = document.createElementNS(svgNS, 'line');
this.pSvg.appendChild(line);
}
catch (err) {
alert("handlClick err: " + err);
}
}
}
//add a click handler for the rect/cell
cell.rect.addEventListener("click", cell.handleClick, false);
//(only seems to work the last time it is executed)
//save the cell object for later use
cells[i][j] = cell;
}
}
}
</script>
(我可以提供完整的页面源代码,但包含这些内容的只是HTML元素。)
问题有两方面:
addEventListener
似乎起作用了。点击所有的其他方块什么也不做。单击最后一个方块(svgTTTsqr22)可以运行cell.handleClick
,但会导致问题2(如下所示)。Chrome (F12)显示除最后一个以外的所有<rect>
元素都没有事件侦听器。cell.handleClick
运行时,它会在第一行(var svgNS = this.pSvg.namespaceURI;
)上失败,出现一个错误,比如“未定义的对象没有一个名为"namespaceURI”的属性,在开发工具中检查显示它失败了,因为this
不是设置为cell
对象,而是设置为单击的SVG <rect>
元素。所以我的问题是:
答:我在这里做错了什么?
我怎么能这样做?
发布于 2015-09-26 15:05:39
1.缺少事件处理程序
使用innerHTML
更改元素的内部结构将导致删除元素的所有子元素,并通过重新解析HTML内容来重建元素的DOM子树。通过删除子元素,所有以前注册的事件侦听器都会丢失,并且在从HTML重新构建DOM时不会自动恢复。为了避免这种行为,最好避免使用innerHTML
,如果可能的话,使用直接的DOM操作。您可以使用这样的方法插入您的<rect>
:
// Use DOM manipulation instead of innerHTML
var rect = document.createElementNS(svg.namespaceURI, 'rect');
rect.setAttributeNS(null, "id", newId);
rect.setAttributeNS(null, "fill", "#00DD00");
rect.setAttributeNS(null, "width", "93");
rect.setAttributeNS(null, "height", "93");
rect.setAttributeNS(null, "x", x);
rect.setAttributeNS(null, "y", y);
svg.appendChild(rect);
事件处理程序内部的this
上下文
每当事件侦听器被调用时,this
都会绑定到由事件触发的元素。但是,在您的代码中,您不需要this
,因为所有信息都可以由参数brd
获得,该参数被传递给函数.tttSetupSquares()
。
handleClick: function (event) {
try {
var svgNS = brd.namespaceURI;
var line = document.createElementNS(svgNS, 'line');
brd.appendChild(line);
}
catch (err) {
alert("handlClick err: " + err);
}
}
有关工作示例,请参阅以下代码段:
function getEl(s) { return document.getElementById(s); }
var svg; // get the TTT svg
var cells = new Array(3);
// execute after HTML has rendered
!(function () {
svg = getEl("svgTTT");
tttSetupSquares(svg);
alert("click-squares are setup.");
}());
// setup the click squares
function tttSetupSquares(brd) {
for (var i = 0; i < 3; i++) {
cells[i] = new Array(3);
for (var j = 0; j < 3; j++) {
var x = 3 + (i * 100);
var y = 3 + (j * 100);
var newId = "svgTTTsqr" + i.toString() + j.toString();
// Use DOM manipulation instead of innerHTML
var rect = document.createElementNS(svg.namespaceURI, 'rect');
rect.setAttributeNS(null, "id", newId);
rect.setAttributeNS(null, "fill", "#00DD00");
rect.setAttributeNS(null, "width", "93");
rect.setAttributeNS(null, "height", "93");
rect.setAttributeNS(null, "x", x);
rect.setAttributeNS(null, "y", y);
svg.appendChild(rect);
//make a cell object to contain all of this
var cell = {
col: i,
row: j,
pSvg: brd,
rect: rect,
handleClick: function (event) {
try {
//console.log(this);
var svgNS = brd.namespaceURI;
var line = document.createElementNS(svgNS, 'line');
line.setAttributeNS(null, "x1", this.x.baseVal.value);
line.setAttributeNS(null, "y1", this.y.baseVal.value);
line.setAttributeNS(null, "x2", this.x.baseVal.value + this.width.baseVal.value);
line.setAttributeNS(null, "y2", this.y.baseVal.value + this.height.baseVal.value);
brd.appendChild(line);
}
catch (err) {
alert("handlClick err: " + err);
}
}
}
//add a click handler for the rect/cell
cell.rect.addEventListener("click", cell.handleClick, false);
//save the cell object for later use
cells[i][j] = cell;
}
}
}
line {
stroke: red;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
id="svgTTT" width="150" height="150" viewBox="0 0 300 300" >
<rect width="3" height="300" x="99" fill="#008d46" />
<rect width="3" height="300" x="199" fill="#000000" />
<rect width="300" height="3" y="99" fill="#008d46" />
<rect width="300" height="3" y="199" fill="#d2232c" />
</svg>
发布于 2015-09-26 13:25:43
正如上面所解释的,“这个”的问题在于它被绑定到一个上下文,而这个上下文并不总是您想要的上下文。这类问题有很多解决办法。从臭名昭著的self=this
戏法到.bind()
。对此也有许多答案,一般来说,可能会有重复的答案。一个很好的答案和一些后续阅读可以在这里找到:
或者在这里:How to change the context of a function in javascript
或者在这里:http://ryanmorr.com/understanding-scope-and-context-in-javascript/
或者在这里:https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/this
虽然,但您的问题的真正答案是非常具体的。在事件处理程序的情况下,有一个"this"-problem的解决方案。您只需实现一个EventListener接口即可。这听起来比现在复杂多了。事实上,这很容易。您的对象只需实现一个函数:.handleEvent
。当您将一个对象传递给addEventListener()函数时,这个函数会自动调用。这方面的好处是,使用这种方法," this“的上下文将自动正确。不需要黑客或解决办法。当然,知道一般情况的解决方案是很好的,但是对于这种特殊情况,.handleEvent
是解决方案。
下面是一个完整的工作示例:
function getEl(s) { return document.getElementById(s); }
var svg; // get the TTT svg
// execute after HTML has rendered
window.onload = function () {
svg = getEl("svgTTT");
tttSetupSquares(svg);
//alert("click-squares are setup.");
}
var cells = new Array(3);
// setup the click squares
function tttSetupSquares(brd) {
for (var i = 0; i < 3; i++) {
cells[i] = new Array(3);
for (var j = 0; j < 3; j++) {
var x = 3 + (i * 100);
var y = 3 + (j * 100);
var rect= document.createElementNS("http://www.w3.org/2000/svg","rect")
rect.setAttribute("x",x);
rect.setAttribute("y",y);
rect.setAttribute("width",100);
rect.setAttribute("height",100);
rect.setAttribute("fill","grey")
brd.appendChild(rect)
var cell = {
col: i,
row: j,
pSvg: svg,
rect: rect,
handleEvent: function (event) {
try {
// this line fails because `this` is the target, not the cell
var svgNS = this.pSvg.namespaceURI;
var line = document.createElementNS(svgNS, 'line');
line.setAttribute("x1",this.rect.getAttribute("x"))
line.setAttribute("y1",this.rect.getAttribute("y"))
line.setAttribute("x2",this.rect.getAttribute("x")*1+this.rect.getAttribute("width")*1)
line.setAttribute("y2",this.rect.getAttribute("y")*1+this.rect.getAttribute("height")*1)
line.setAttribute("stroke","red")
this.pSvg.appendChild(line);
document.getElementById("out").innerHTML="rect("+this.col+","+this.row+") was clicked"
}
catch (err) {
alert("handlClick err: " + err);
}
}
}
//add a click handler for the rect/cell
cell.rect.addEventListener("click", cell, false);
//(only seems to work the last time it is executed)
//save the cell object for later use
cells[i][j] = cell;
}
}
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
id="svgTTT" width="150" height="150" viewBox="0 0 300 300" >
<rect width="3" height="300" x="99" fill="#008d46" />
<rect width="3" height="300" x="199" fill="#000000" />
<rect width="300" height="3" y="99" fill="#008d46" />
<rect width="300" height="3" y="199" fill="#d2232c" />
</svg>
<div id="out"></div>
在EventHandlers的情况下,这是正确的解决方案,其他一切都是黑客!
发布于 2015-09-26 11:09:49
一些建议:
您可以研究如何使用事件委托。如果您使用像jQuery这样的框架或库,或者使用角度或响应,它将自动为您执行事件委托。在单独的DOM元素上设置许多事件处理程序可能会影响性能。相反,您可以做的是在包装元素上设置一个“单击”处理程序,并使用event.target
属性查看实际单击的元素。
svg.addEventListener("click", function (e) {
if (e.target.nodeName === "rect" && (/^svgTTTsqr/).test(e.target.id)) {
// Use a regexp on e.target.id to find your
// cell object in `cells`
}
});
regexp可能有点脏,所以您应该使用数据属性。
// Generating the HTML
brd.innerHTML += "<rect id='"+newId+"' data-i='" + i + "' data-j='" + j + "' "
// The event handler:
svg.addEventListener("click", function (e) {
if (e.target.nodeName === "rect" && (/^svgTTTsqr/).test(e.target.id)) {
var i = e.target.getAttribute("data-i");
var j = e.target.getAttribute("data-j");
var cell = cells[i][j];
cell.handleClick();
}
});
如果这样做,还可以轻松地进行另一个性能调整,即首先生成整个HTML字符串,并在一个操作中将其附加到DOM中,因为不再需要在循环时将HTML插入DOM并添加事件侦听器。
至于你的问题,
1)对不起,不能帮您:(需要设置一个可执行的示例并四处查看,在读取代码时什么都想不出来。无论如何,我将发布这个答案,因为希望上面解释的事件委托解决方案能够解决问题。
( 2)被称为“原始函数”的原始函数将其“此”绑定到其调用的任何范围。调用方还可以显式设置“this”绑定到的内容。解决方案是创建一个被包装的新函数,这样‘这’就会被迫成为你想要它成为的样子。使用内置的function () {}.bind(cell)
,它将返回一个包装原始函数的新函数,而在原始this
中,不管bind
返回的函数是什么上下文,总是将其设置为cell
。
https://stackoverflow.com/questions/32800782
复制