今天遇到这个问题,发布以防其他人有同样的问题.
var execBtn = document.createElement('input');
execBtn.setAttribute("type", "button");
execBtn.setAttribute("id", "execBtn");
execBtn.setAttribute("value", "Execute");
execBtn.setAttribute("onclick", "runCommand();");
Run Code Online (Sandbox Code Playgroud)
结果是让IE在动态生成的元素上运行onclick,我们不能使用setAttribute.相反,我们需要使用包含我们想要运行的代码的匿名函数在对象上设置onclick属性.
execBtn.onclick = function() { runCommand() };
Run Code Online (Sandbox Code Playgroud)
不好的想法:
你可以做
execBtn.setAttribute("onclick", function() { runCommand() });
Run Code Online (Sandbox Code Playgroud)
但根据@scunliffe,它将在非标准模式下在IE中中断.
你完全不能这样做
execBtn.setAttribute("onclick", runCommand() );
Run Code Online (Sandbox Code Playgroud)
因为它立即执行,并将runCommand()的结果设置为onClick属性值,也不能这样做
execBtn.setAttribute("onclick", runCommand);
Run Code Online (Sandbox Code Playgroud) 任何简单的方法来检测它?我想在进行迁移rake时跳过envirmonment.rb中的一些代码.
有时你的字符串必须符合某个像素宽度.此功能尝试有效地执行此操作.请在下面发布您的建议或重构:)
function fitStringToSize(str,len) {
var shortStr = str;
var f = document.createElement("span");
f.style.display = 'hidden';
f.style.padding = '0px';
document.body.appendChild(f);
// on first run, check if string fits into the length already.
f.innerHTML = str;
diff = f.offsetWidth - len;
// if string is too long, shorten it by the approximate
// difference in characters (to make for fewer iterations).
while(diff > 0)
{
shortStr = substring(str,0,(str.length - Math.ceil(diff / 5))) + '…';
f.innerHTML = shortStr;
diff = f.offsetWidth - len; …
Run Code Online (Sandbox Code Playgroud)