如何使用typescript找到html "占位符"属性并在函数中使用该元素?
这个问题很宽泛。例如给定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
});
标题>你的HTML输入元素:
<input id='randomId' type='text' val='value' placeholder='This text is just a placeholder!'>
访问元素:
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 {
}
检查是否存在属性:
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!'