如何使用打字稿找到“占位符”属性?

时间:2014-07-23 10:36:44

标签: typescript each placeholder

如何找到html"占位符"属性使用 typescript 并在函数中使用该元素?

2 个答案:

答案 0 :(得分:0)

这个问题非常广泛。以html:

为例
<input placeholder="tada" id="foo"/> 

以下作品:

alert(document.getElementById('foo').getAttribute('placeholder'))

更新

修改评论:

$('input[type = "text"][placeholder]')
           .each(function () { 
                    console.log(this.getAttribute('placeholder')); // this is the DOM element
           });

答案 1 :(得分:0)

您的 HTML 输入元素:

<input id='randomId' type='text' val='value' placeholder='This text is just a placeholder!'>

在javascript中访问 元素

var inputElement = document.getElementById('randomId');

检查以获取javascript中占位符属性的浏览器支持

// I like having such a simple class ...
var Browser = {
  CanAttribute: function (name) {
    return name in document.createElement('input'); 
  }
}

// ... so you can easily check if your browser supports the placeholder attribute.
if (Browser.CanAttribute('placeholder')) {

}
else {

}

在javascript中检查 是否存在属性

if ('placeholder' in inputElement) {
  // You can access inputElement.placeholder
}
else {
  // Accessing inputElement.placeholder will throw an ReferenceError-Exception
}

通过javascript检索占位符属性

var placeholderText = inputElement.placeholder;
console.log(placeholderText); // 'This text is just a placeholder!'

通过javascript设置占位符属性

inputElement.placeholder = 'This placeholder text overrides the default text!';
console.log(placeholderText); // 'This placeholder text overrides the default text!'