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

问题描述

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...