问题描述
如描述中所示:我正在尝试使用存储在变量中的字符串来格式化HTML接口名称。 到目前为止,我已经尝试过:
function enableInputFieldTabSupportByTagAndId(tagName,HTMLInterfaceName,textareaId,tabSize) {
// this returns "Uncaught TypeError: Cannot set property 'getcaretposition' of undefined'"
`HTML${HTMLInterfaceName}Element`.prototype.getcaretposition = function () {
//return the caret position of the input field
return this.selectionStart;
// this returns "Uncaught TypeError: Cannot set property 'getcaretposition' of undefined"
$("HTML" + HTMLInterfaceName + "Element").prototype.getcaretposition = function () {
//return the caret position of the input field
return this.selectionStart;
// this is valid but only for textarea interface
HTMLTextAreaElement.prototype.getcaretposition = function () {
//return the caret position of the input field
return this.selectionStart;
};
稍后使用第三个选项可以正常工作,但仅适用于textarea标签:
// this returns "Uncaught TypeError: inputField.getcaretposition is not a function
at HTMLInputElement.inputField.onkeydown" for input tag
var inputField = document.getElementsByTagName(tagName)[textareaId];
解决方法
您需要使用括号表示法从window
访问元素,而不是将字符串包装为jQuery对象。
window["HTML" + HTMLInterfaceName + "Element"].prototype.getCaretPosition = function(){
//...
}