简体   繁体   English

使用JavaScript更改HTML标签属性

[英]Changing HTML tag attributes with javascript

I'm trying to get what I think is a really nice bit of HTML5 in my website - the placeholder attribute for input fields. 我正在尝试获取我认为在我的网站中非常好的HTML5的内容- input字段的占位符属性。

But the way I've got it in my website degrades badly. 但是我在网站上获取它的方式严重恶化。 Because I've skipped labels for the fields and used the placeholder as its label. 因为我跳过了字段的标签,并使用了占位符作为其标签。

At the moment I have several input fields with placeholders, they look like this: 目前,我有几个带有占位符的输入字段,它们看起来像这样:

<input placeholder="hereismyplaceholder" />

But where HTML5 placeholder support is not available, I would like all of the input fields with placeholders to change to this. 但是在没有HTML5占位符支持的地方,我希望所有带有占位符的输入字段都更改为此。 Obviously with their equivalent placeholder text: 显然带有其等效的占位符文本:

<input onblur="if (this.value == '') {this.value = 'hereismyplaceholder';}" onfocus="if (this.value == 'hereismyplaceholder') {this.value = '';}" value="hereismyplaceholder" />

So I've pulled in Modernizr , and I'm getting it to detect the placeholders with the following javascript: 因此,我引入了Modernizr ,并使用以下javascript来检测占位符:

if (Modernizr.input.placeholder) {
} else {
// BUT I NEED SOMETHING IN HERE
}

But I have no idea what to do now. 但是我不知道现在该怎么办。 Because I have no experience with javascript, I'm not a developer. 因为我没有使用javascript的经验,所以我不是开发人员。

The simplest solution would be the best please. 最简单的解决方案是最好的解决方案。 I'm not fussed about good practice, I just want it to work for now. 我不对良好实践大惊小怪,我只希望它现在可以工作。

There is an example here, http://www.modernizr.com/docs/#input 这里有一个示例, http://www.modernizr.com/docs/#input

For your specific use case, the code should be 对于您的特定用例,代码应为

// if placeholder isn't supported:
if (!Modernizr.input.placeholder){
  // use a input hint script
  setInputHint(document.getElementById('idoftheinputelement'),'hereismyplaceholder');
}

You didn't ask for jQuery, but I didn't want to worry about cross-browser issues: 您没有要求使用jQuery,但我不想担心跨浏览器的问题:

if (!Modernizr.input.placeholder) {
  $("input[type=text]")
  .focus(function(e){
      if (this.value == $(this).attr('placeholder')) {
         this.value = '';
      }         
  })
  .blur(function(e){
    setPlaceholder(this);
  }).each(function(index, el){
    setPlaceholder(el);
  });

  function setPlaceholder(el) {
    if (el.value  == '') {
        el.value = $(el).attr('placeholder');
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM