我正在与html,js和css.i的移动网站上工作。我已经通过HTML5 DOM创建标签并分配功能给它。这不管用。
我的html代码(我已经通过DOM方法尝试过了);
<script>
var addExhibits = document.getElementById('mycontent');
function mytest()
{
var div = document.createElement('div');
div.id = 'rateMe';
var anchor = document.createElement('a');
anchor.id="_1";
anchor.onclick = rateIt(this);
anchor.onmouseover=rating(this);
anchor.onmouseout=off(this);
div.appendChild(anchor);
addExhibits.appendChild(div);
}
</script>
<body><div id='mycontent' title="Rate Me..."></body>
代码(静态创建的标签-工作正常)
<div id="rateMe" title="Rate Me...">
<a onclick="rateIt(this)" id="_1" onmouseover="rating(this)" onmouseout="off(this)"></a>
</div>
rate(this)是外部JS(http://reignwaterdesigns.com/ad/tidbits/rateme/)中的函数
发布于 2013-07-15 11:13:31
您的事件处理程序只需在此处指定各个函数调用的结果:
anchor.onclick = rateIt(this);
anchor.onmouseover=rating(this);
anchor.onmouseout=off(this);
我假设您希望它们在发生事件的情况下执行:
var that = this;
anchor.onclick = function(){ rateIt(that); };
anchor.onmouseover = function(){ rating(that); };
anchor.onmouseout= function(){ off(that); };
发布于 2013-07-15 11:19:46
您不会在任何地方调用mytest()函数。这是我看到的第一件事。另一件事是您将脚本放在div (mycontent)之上,因此在读取脚本时div尚未创建。但是我不完全理解你在这里的目的是什么,或者你的问题到底是什么。
发布于 2013-07-15 11:35:59
你不需要通过这个。
您可以通过多种方式访问函数中的元素。
var addExhibits=document.getElementById('mycontent'),
rateIt=function(e){
e=e||window.event;
var target=e.target||e.srcElement;//polyfill for older browser
console.log(this,target);
},
rating=function(e){
console.log(this,e.target);
},
off=function(e){
console.log(this,e.target);
},
mytest=function(){
var div=document.createElement('div'),
a=document.createElement('a');
div.id='rateMe';
a.id="_1"; // id's shouldn't contain _ - & numbers(1st letter) even if it works.
a.onclick=rateIt;
a.onmouseover=rating;
a.onmouseout=off;
div.appendChild(a);
addExhibits.appendChild(div);
};
这样也不会造成内存泄漏。
附言:您使用的外部js示例写得非常糟糕。
要使您的示例工作,您需要将外部js中奇怪的me/num/sel变量更改为适当的变量(this/e.target/e.srcElement)。
https://stackoverflow.com/questions/17652870
复制相似问题