将input元素属性定义为defineObject javascript方法

时间:2017-11-28 21:50:44

标签: javascript html css

如何使用以下内容定义placeholderpattern等属性

Object.defineProperty(inputProto, 'placeholder', {value: 20, writable: true});

可行,但当我在HTML上搜索时,会显示undefined

如何使用Web ComponentJavaScript中定义htmlElements属性?我不想在HTML中设置它们。

代码:

var inputProto = Object.create(HTMLInputElement.prototype);
//funciones del js API (prototype del componnente)   
inputProto.onClear = function() {
    this.value = "";
    this.style.position = "static";
    this.placeholder = "New Text";
}

inputProto.setPos = function(x, y) {
    this.style.top = x + "px";
    this.style.left = y + "px";
    this.style.position = "relative";
}

inputProto.setDimensions = function(width, height) {
    this.style.width = width + "px";
    this.style.height = height + "px";
}

inputProto.caps = function(input) {
    input = this.value;
    var regEx = /[A-Z]/;
    var match = regEx.test(input);
    if (match) {
        alert("Valid")
    } else {
        alert("Not valid")
    }
}

inputProto.lowerCaps = function(input) {
    input = this.value;
    var regEx = /[^A-Z]/;
    var match = regEx.test(input);
    if (match) {
        alert("Valid")
    } else {
        alert("Not valid")
    }
}

var EgComponent = document.registerElement('eg-input', {
    prototype: inputProto,
    extends: 'input'
});

var egcomp = new EgComponent();
//function de componente ya creado en el DOM
function test() {
    egcomp.onClear();
    egcomp.setDimensions(250, 15);
}

function test1() {
    egcomp.setDimensions(350, 15);
}

function test2() {
    egcomp.caps();
}

function test3() {
    egcomp.lowerCaps();
}

function test4() {
    egcomp.setPos(30, 580);
}
//metiendo el componente al html desde el dom
document.body.appendChild(egcomp);

1 个答案:

答案 0 :(得分:1)

您使用Object.defineProperty设置的属性值为undefined,因为您在原型而不是EgComponent实例上设置它们:

/* That's what you do. */
Object.defineProperty(inputProto, "placeholder", {value: 20, writable: true});

valuepatternplaceholder等属性是特定于实例的,而不是特定于原型的属性,因此为了实际为EgComponent的实例设置这些属性,您必须使用defineProperty上的egcomp而不是inputProto

/* That's what you should do to set the property. */
Object.defineProperty(egcomp, "placeholder", {value: 20, writable: true});

如果您如上所示定义属性,则该属性将设置为egcomp,如果您在控制台中键入20,则可以看到它是egcomp.placeholder;。但是,您很容易注意到,即使设置了placeholder的{​​{1}}属性,也未设置egcomp属性。如果在控制台中键入HTML,则可以验证。要解决这个问题,你可以抛弃egcomp.getAttribute("placeholder");并以老式的方式设置属性:

Object.defineProperty

查看以下代码段以了解其工作原理。

<强>段:

&#13;
&#13;
/* That's what you should do to set the property and HTML attribute. */
egcomp.placeholder = 20;
&#13;
&#13;
&#13;