2

管理者がアカウントを作成、一時停止するためのフォームを表示する以下のコードがあります

echo "<FORM name=\"admin\" action=\"\" enctype=\"multipart/form-data\">";
echo "<select onchange=\"ChangeType();\" name=\"action\" id=\"action\">";
echo "<option value=\"select\">--Select--</option>";
echo "<option value=\"create\">Create Account</option>";
echo "<option value=\"suspend\">Suspend Account</option>";
echo "</select><br><br>";
echo "<div id=\"data\">";
echo "</div>";
echo "<input type=\"button\" name=\"button\" onclick=\"AccountAction()\" value=\"Submit\">";
echo "<input type=\"reset\" id=\"reset\" value=\"Reset\" onclick=\"ResetForm();\">";
echo "</FORM>";

ユーザーが ChangeType() を呼び出したときに DOM 内に要素を動的に作成するための JavaScript

function ChangeType()
{
    var type = document.getElementById("action").options[document.getElementById("action").selectedIndex].value;
    if(type=="select")
    {
        document.getElementById('data').innerHTML = "";
    }
    if(type=="create")
    {
        document.getElementById('data').innerHTML = "<input id=\"username\" placeholder=\"Username\" type=\"text\" name=\"username\"><br><br>";
        document.getElementById('data').innerHTML += "<input id=\"password\" placeholder=\"Password\" type=\"password\" name=\"password\"><br><br>";
        return;
    }
    if(type=="suspend")
    {
        document.getElementById('data').innerHTML = "<input id=\"username\" placeholder=\"Username\" type=\"text\" name=\"username\"><br><br>";
        return;
    }
}

コードは正常に動作しますが、動的に作成されたユーザー名とパスワードの入力タイプのプレースホルダーを取得できません

私はすでに 動的に作成されたフォーム要素にjQueryプレースホルダーを追加するを見てきました

しかし、テキストエリア内を1回クリックしてから外側をクリックしたときにのみプレースホルダーが表示されるため、役に立ちません。

4

2 に答える 2

1

あなたはこのようにする必要があります:

document.getElementById('data').setAttribute("placeholder", "placeholder value");

あなたのコードで:

function ChangeType() {
var type = document.getElementById("action").options[document.getElementById("action").selectedIndex].value;
if (type == "select") {
    document.getElementById('data').innerHTML = "";
    document.getElementById('data').setAttribute("placeholder", "placeholder value");
}
if (type == "create") {
    document.getElementById('data').innerHTML = "<input id=\"username\" placeholder=\"Username\" type=\"text\" name=\"username\"><br><br>";
    document.getElementById('data').innerHTML += "<input id=\"password\" placeholder=\"Password\" type=\"password\" name=\"password\"><br><br>";
    document.getElementById('data').setAttribute("placeholder", "placeholder value");
    return;
}
if (type == "suspend") {
    document.getElementById('data').innerHTML = "<input id=\"username\" placeholder=\"Username\" type=\"text\" name=\"username\"><br><br>";
    document.getElementById('data').setAttribute("placeholder", "placeholder value");
    return;
}}

Jquery (ブラウザ互換ソリューション) の使用:

$("#data").attr("placeholder", "placeholder value");
于 2013-05-28T05:34:33.367 に答える