我有一个div:
<div id="test" style="width:auto; height:auto;">
</div>
还有一个功能:
$(function() {
$("#test").attr("contentEditable", "true");
$("#test")
.attr("tabindex", "0")
.keydown(function(){ alert(1); return false; })
.mousemove(function(){ alert(2); return false; });
});
如何在不包含 JQuery 库的情况下在 JavaScript 中实现此代码?
你可以在javascript中这样做,而无需使用jquery,演示可用在这里 JsFiddle你可以把它放在 body 的 onload 方法中,然后它将调用 body 的 onload,或者只是把它放在所有控件下面的脚本部分而不把它放在函数中,然后它会在文档准备好时调用,就像 jquery 方法 $().ready();
var test = document.getElementById('test');
test.setAttribute("contentEditable", "true");
test.setAttribute("tabindex", "0");
test.onkeydown = function(event) { alert("KeyDown");}
test.onmousemove = function(event) { alert("MouseMove");}
function runme() {
var elm = document.getElementById("test");
elm.contentEditable = "true";
elm.tabIndex = 0;
elm.onkeydown = function() { alert(1); return false; };
elm.onmousemove = function() { alert(2); return false; };
}
if(window.addEventListener)
window.addEventListener("load", runme, false);
else
window.attachEvent("onload", runme);
Adil 的想法是正确的,但为了稍微改进一下,您可以将元素存储在变量中,这样您就不必每次都调用来获取元素。所以我会把它改成这样:
var t = document.getElementById('test');
t.setAttribute("contentEditable", "true");
t.setAttribute("tabindex", "0");
t.onkeydown = function(event) { alert("KeyDown");}
t.onmousemove = function(event) { alert("MouseMove");}
支持阿迪尔击败我并提供 jsfiddle 链接:)
已更新:没关系,因为您刚刚更新了帖子