我对javascript有疑问.我在javascript中编写了一个函数,并在.html文件中编写了该函数.
但是,当我单击该按钮时,它会在IE 8中显示"对象不支持此属性或方法"错误.
谁能帮我?谢谢.
function colour (colour) {
var selectTxt =
window.getSelection() ||
document.getSelection() ||
(document.selection ? document.selection.createRange().text : ''),
targetHTML = document.getElementById('text'); // text is a id in HTML
targetHTML.innerHTML =
targetHTML.innerHTML.replace(
RegExp(selectTxt),
'<span class="' + colour + '">'+selectTxt+'</span>');
}
// HTML
<input type="button" onclick="colour('green')" value="Green"/>
<p id='text'>I live in ABC and I am working in ABC company.</p>
Run Code Online (Sandbox Code Playgroud)
您在检查它们是否存在之前执行这些方法,因此当不支持此方法时(例如window.getSelection),您确实会收到错误.
将此类函数添加到您的代码中:
function GetSelectedText() {
if (window.getSelection)
return window.getSelection();
if (document.getSelection)
return document.getSelection();
if (document.selection)
return document.selection.createRange().text;
return "";
}
Run Code Online (Sandbox Code Playgroud)
然后只需:
var selectTxt = GetSelectedText();
Run Code Online (Sandbox Code Playgroud)