如果“值”,则如何添加占位符属性字段是空的 [英] How to add a placeholder attribute if "value" field is empty

查看:180
本文介绍了如果“值”,则如何添加占位符属性字段是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您的文本输入字段的value属性为空,是否有办法添加占位符属性(占位符标记,而不是defaultvalue和类似方法)?

Is there a way to add a placeholder attribute (placeholder tag, not "defaultvalue" and similar approaches) if you have an text input field that has "value" property empty?

我在这里看过很多类似的问题,但大多数都使用defaultvalue。我需要占位符标签,另外我根本不能影响HTML输出。

I have seen many similar questions here, but most of them use defaultvalue. I need placeholder tags and additionally I can't influence HTML output at all.

这是给定的HTML输出示例:

This is the given HTML output example:

<input type="text" value="" name="textbox" id="edit-textbox">


推荐答案

我建议采用以下任何一种方法:

I'd suggest any one of the following approaches:

$('input:text').each(
    function(i,el) {
        if (!el.value || el.value == '') {
            el.placeholder = 'placeholdertext';
            /* or:
            el.placeholder = $('label[for=' + el.id + ']').text();
            */
        }
    });

JS小提琴演示使用 el.placeholder ='placeholdertext'

JS小提琴演示使用 el.placeholder = $('label [for ='+ el.id + ']')。text()

或者您可以使用数组存储各种占位符:

Or you could use an array to store the various placeholders:

var placeholders = ['Email address', 'favourite color'];

$('input:text').each(
    function(i,el) {
        if (!el.value || el.value == '') {
            el.placeholder = placeholders[i];
        }
    });​

JS Fiddle demo

为特定元素指定特定占位符:

To specify a particular placeholder for a particular element:

var placeholders = {
    'one' : 'Email address',
    'two' : 'Favourite color'
};

$('input:text').each(
    function(i,el) {
        if (!el.value || el.value == '') {
            el.placeholder = placeholders[el.id];
        }
    });​

JS Fiddle demo

如果特定输入输入的占位符对象中不存在条目,则添加了一个catch / fall-back

Added a catch/fall-back in the event that an entry doesn't exist in the placeholders object for a particular input:

var placeholders = {
    'oe' : 'Email address', // <-- deliberate typo over there
    'two' : 'Favourite color'
};

$('input:text').each(
    function(i,el) {
        if (!el.value || el.value == '') {
            el.placeholder = placeholders[el.id] || '';
        }
    });​

JS Fiddle demo

这篇关于如果“值”,则如何添加占位符属性字段是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆