2017-11-16 9 views
0

テキストフィールドが空のままになっている場合は、赤いアスタリスクを追加するこのコードを使用します。ドキュメントが上記のテキストフィールドで入力を検出するとアスタリスクが消えるようにしたい。私はまた、より多くのアスタリスクが追加されないようにしたい。IF既に存在し、テキストフィールドはまだ空である。私はIF ELSEステートメントを実行しようとしましたが、エラーが発生します。何か助けてくれてありがとう。何のアスタリスクがない場合、フィールドが空白の場合は空のテキストフィールドに複数のアスタリスクが生成される

と:

const button = document.getElementById('button') 
 
const listdiv = document.querySelector('.listdiv') 
 
var urlinput = document.getElementById('text').value 
 

 
button.addEventListener('click', function() { 
 
    // Get URL and add it into a link 
 
    let createA = document.createElement('a') 
 
    createA.href = urlinput 
 
    createA.textContent = urlinput 
 

 
    // Get description and add it to the link 
 
    let descrInput = document.getElementById('description').value 
 
    let strong = document.createElement('strong') 
 
    strong.textContent = descrInput 
 

 
    if (urlinput.trim() !== '') { 
 
    listdiv.appendChild(strong) 
 
    listdiv.appendChild(createA) 
 
    } else { 
 
    var ast = document.querySelector('.ast') 
 
    var createAst = document.createTextNode('*') 
 
    text.style.border = '1px solid #ff0000' 
 
    ast.style.color = '#ff0000' 
 
    ast.appendChild(createAst) 
 
    } 
 
})
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
 
    <link href="style.css" rel="stylesheet" type="text/css"> 
 
    <title>Meine Testseite</title> 
 
</head> 
 

 
<body> 
 

 
    <div class="formdiv"> 
 
    <form> 
 
     <input type="text" name="" placeholder="Enter URL" id="text" autofocus> 
 
     <div class="ast"></div> 
 
     <input type="text" name="" placeholder="Link description" id="description"> 
 
     <input type="button" value="Add" class="button" id="button"> 
 
    </form> 
 
    </div> 
 

 
    <div class="listdiv"> 
 

 
    </div> 
 

 
    <script src="js.js"></script> 
 
</body> 
 

 
</html>

答えて

0

ただ、個人の好みが、私は、問題のよりよいハンドルを得るためにあなたのif文の周りになるかもしれませんすでに表示されている場合は、アスタリスクを追加します。 (省略可能)フィールドが空白で、アスタリスクがある場合は、フィールドが空白でない場合はelse。

あなたはdocument.querySelector('.ast').innerHTMLのようなものを使用してアスタリスクdiv要素の値を取得し、あなたのif声明の中で、それを含めることができます。

if (urlinput.trim() === '' && document.querySelector('.ast').innerHTML === "") { 
    add an asterisk 
} else if (urlinput.trim() === '' && document.querySelector('.ast').innerHTML === "*" { 
    don't add an asterisk 
} else { 
    appendChild as you've already got them 
} 

この解決策のトリックは1つのアスタリスクがある場合、それは本当に唯一の仕事だろうということですフィールドに入力します。あなたの質問に基づいて、その仮定が成り立ちます。それが悪い仮定なら、私に知らせてください。

+0

ありがとうございます。それは私を前進させるはずです。明確にするために、「アスタリスクを追加しないでください」と言うとき、コードはどのように見えますか?ちょうど '戻り'? – Helle

関連する問題