首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Jimdo:使用javascript / jquery向html添加占位符

Jimdo:使用javascript / jquery向html添加占位符
EN

Stack Overflow用户
提问于 2018-08-24 07:45:00
回答 4查看 688关注 0票数 1

由于网络主机"Jimdo“的限制,我无法更改html文档以将”占位符“插入到文本字段中。有没有办法使用javascript或jquery添加该属性?

我已经尝试了一些我在这里找到的代码,但它对我不起作用。也许我只是把括号放错了,或者代码与Jimdo的head-area不兼容……

这是来自吉姆多的代码。

<input type="text" name="url" id="url9611056885" value="" class="single">

截图:

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-08-24 08:07:19

不需要jQuery,一个普通的JavaScript解决方案。接受两个参数的函数第一个参数表示元素本身或表示其IDstring,第二个参数是占位符string

function addPlaceholder(el, ph) {
  if(typeof el === 'string') {
    el = document.getElementById(el);
  } else if(el instanceof HTMLElement === false) {
    console.log('Not a valid HTML element.');
    return false;
  }
  el.setAttribute('placeholder', ph);
  return true;
}
addPlaceholder('input1', "a placeholder for input 1"); // sending the ID of the input element
addPlaceholder(document.getElementById('input2'), "a placeholder for input 2"); // sending the input element itself
addPlaceholder(window, "will not work!"); // sending a non-valid HTML element here the window object, a log in the console will appear and the function returns false.
<input type="text" id="input1" />
<input type="text" id="input2" />

票数 1
EN

Stack Overflow用户

发布于 2018-08-24 07:48:54

使用jQuery .attr()

$("#url9611056885").attr("placeholder","I'm a placeholder");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="url" id="url9611056885" value="" class="single">

票数 4
EN

Stack Overflow用户

发布于 2018-08-24 07:48:16

您可以使用.setAttribute来做到这一点。

document.getElementById("url9611056885").setAttribute("placeholder", "Hey! I'm alive!");
<input type="text" name="url" id="url9611056885" value="" class="single">

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51995693

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档