使用 Jquery 添加占位符属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25049731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:01:52  来源:igfitidea点击:

Adding placeholder attribute using Jquery

jquery

提问by krispykim

I have a simple problem. I just want to add a placeholder on an input. Here's the code:

我有一个简单的问题。我只想在输入上添加一个占位符。这是代码:

HTML:
<input type="text" name="link" class="hidden">

JQuery:
var link = document.querySelector('.link');
    link.style.display='block';
    link.classList.remove('hidden');
    if(val === 1)  // for a movie
        link.classList.add('placeholder="Add Movie Title. ."');
    else  // for an external link
        link.classList.add('placeholder="Add External Link . ."');

As you can see, the placeholder doesn't work because the syntax is wrong. I searched related solutions to my problem but they use a different method like this

如您所见,占位符不起作用,因为语法错误。我搜索了我的问题的相关解决方案,但他们使用了这样的不同方法

$("").attr("placeholder", "Type here to search");});

but I need something that is similar to what I used with adding style, but I'm not sure if there's other way to do it. Is there a similar way?

但我需要一些类似于我添加样式时使用的东西,但我不确定是否还有其他方法可以做到。有没有类似的方法?

回答by Amit Joki

You just need this:

你只需要这个:

$(".hidden").attr("placeholder", "Type here to search");

classListis used for manipulating classes and not attributes.

classList用于操作类而不是属性。

回答by jinggoy

This line of code might not work in IE 8 because of native support problems.

由于本机支持问题,这行代码可能无法在 IE 8 中运行。

$(".hidden").attr("placeholder", "Type here to search");

You can try importing a JQuery placeholder pluginfor this task. Simply import it to your libraries and initiate from the sample code below.

您可以尝试为此任务导入JQuery 占位符插件。只需将其导入您的库并从下面的示例代码启动。

$('input, textarea').placeholder();

回答by chiwangc

Try something like the following if you want to use pure JavaScript:

如果您想使用纯 JavaScript,请尝试以下操作:

document.getElementsByName('link')[0].placeholder='Type here to search';

回答by azeem

you just need to put this

你只需要把这个

($('#{{ form.email.id_for_label }}').attr("placeholder","Work email address"));

($('#{{ form.email.id_for_label }}').attr("placeholder","工作邮箱地址"));

($('#{{ form.password1.id_for_label }}').attr("placeholder","Password"));

($('#{{ form.password1.id_for_label }}').attr("placeholder","Password"));