由于网络主机"Jimdo“的限制,我无法更改html文档以将”占位符“插入到文本字段中。有没有办法使用javascript或jquery添加该属性?
我已经尝试了一些我在这里找到的代码,但它对我不起作用。也许我只是把括号放错了,或者代码与Jimdo的head-area不兼容……
这是来自吉姆多的代码。
<input type="text" name="url" id="url9611056885" value="" class="single">
截图:
发布于 2018-08-24 08:07:19
不需要jQuery,一个普通的JavaScript
解决方案。接受两个参数的函数第一个参数表示元素本身或表示其ID
的string
,第二个参数是占位符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" />
发布于 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">
发布于 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">
https://stackoverflow.com/questions/51995693
复制相似问题