如何使用字符串变量格式化 HTML 接口名称

How to format HTML interface name using string variable

如描述:我正在尝试使用存储在变量中的字符串来格式化 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(){
  //...
}