Как найти атрибут html "placeholder" с помощью машинописного текста и использовать этот элемент внутри функции?
Этот вопрос довольно широк. В качестве примера приведен 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
});
.attribute
если вам нужен программный доступ к атрибуту в JavaScript. Используйте .getAttribute()
и .setAttribute()
когда вы хотите работать с DOM как есть (например, только с литеральным текстом).
Входной элемент HTML:
<input id='randomId' type='text' val='value' placeholder='This text is just a placeholder!'>
Доступ к элементу в javascript:
var inputElement = document.getElementById('randomId');
Проверка поддержки браузера атрибута placeholder в 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
}
Получение атрибута placeholder через javascript:
var placeholderText = inputElement.placeholder;
console.log(placeholderText); // 'This text is just a placeholder!'
Установка атрибута placeholder через javascript:
inputElement.placeholder = 'This placeholder text overrides the default text!';
console.log(placeholderText); // 'This placeholder text overrides the default text!'
$(this).attr('placeholder')
вы можете просто написать это так: this.placeholder