【问题标题】:How do you find the "placeholder" attribute using typescript?您如何使用打字稿找到“占位符”属性?
【发布时间】:2014-07-23 20:28:23
【问题描述】:

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

【问题讨论】:

  • 我在 jquery 中做了同样的事情......如果你能在找到属性后告诉我使用元素的方法,我会很高兴
  • 那么你是想定位所有具有占位符属性的元素,然后对这些元素做一些事情,还是我误解了?此外,您在评论中提到您在 jQuery 中做了同样的事情。这是否意味着您不想在这里使用 jQuery?

标签: typescript each placeholder


【解决方案1】:

这个问题相当广泛。作为给出 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
           });

【讨论】:

  • 如果您想以编程方式访问 JavaScript 中的属性,您应该始终使用直接的 .attribute 方法。如果您希望按原样处理 DOM(例如,仅文本),请使用 .getAttribute().setAttribute()
  • ('input[type = "text"][placeholder]').each(function () { console.log($(this).attr('placeholder')); // 错误在这里 } 你能告诉我一个不同的方式来访问这个里面的元素吗
  • 您遇到了什么样的错误?出于好奇,您是否在为 jQuery 使用任何类型的 TypeScript 定义文件?
  • 谢谢...正是我想要的
  • @basarat OP 不想知道如何使用 jQuery 来实现这一目标。他想用打字稿来做。
【解决方案2】:

您的 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!'

【讨论】:

  • ('input[type = "text"][placeholder]').each(function () { console.log($(this).attr('placeholder')); // 错误在这里 } 你能告诉我一个不同的方式来访问这个里面的元素吗
  • 当然 :) 而不是 $(this).attr('placeholder') 你可以这样写:this.placeholder
猜你喜欢
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 2014-06-20
  • 2011-09-17
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
  • 2018-02-10
相关资源
最近更新 更多