我创建了一个函数,以便只要通过按钮调用该函数就会加载该函数。但它只有在我刷新页面时才有效,但是当我点击交换按钮时它不起作用。
以下是链接http://www.onlinedemowebsite.com/design/swatch/drag-and-drop/try3.html
任何人都可以帮我解决问题。
由于
答案 0 :(得分:1)
您在交换按钮上有onclick =“shuffle()”,并且该事件将在其中触发的全局范围中未定义该函数。将函数移动到窗口范围,或创建DOM节点并将实际事件附加到它而不是使用document.writeln
另外,shuffle函数使用document.writeln,一个例子是修改它并做这样的事情:
function shuffle(){
//organize and sort your letters here
var letters = ....
//query for all elements with class = 'letters' use a library if you want full browser support.
var letter_nodes = document.querySelectorAll("div.letters");
for ( var i = 0, n = letter_nodes.length; i<n; ++i ) {
letter_nodes[i].innerHTML = letters[i]; // letters and letter_nodes array should have the same length.
}
}
编辑:
将您的随机播放功能更改为:
var letters=['A','B','E','F','O','M','I','T']; //to access letters.length in the other function
function shuffle(){
letters.sort(function(){return 0.5 - Math.random();});
var letter_nodes = document.getElementById('lettersContainer');
letter_nodes = letter_nodes.getElementsByTagName('div');
for ( var i = 0, n = letter_nodes.length; i<n; ++i ) {
letter_nodes[i].innerHTML = letters[i];
}
return false;
}
然后更改创建容器的部分(在print_2d_string_array中)
document.writeln ("<a href='#' onclick='return shuffle()' class='swap'>Swap</a>");
document.writeln ("<div id='lettersContainer'>");
for ( var i = 0; i < letters.length; ++i ) {
document.writeln ("<div class='letters'></div>");
}
shuffle();
document.writeln ("</div>"); /* lettersContainer end */