String concatenation error
I have a HTMl form
<form action="" method="post" enctype="multipart/form-data">
<p>
Banner Ad Name :<br />
<input type="text" name="bannerAdName" id="bannerAdName" />
</p>
<p>
Your web page :<br />
<input type="text" name="bannerAdWeb" id="bannerAdWeb" />
</p>
<p>
Ad image :<br />
<input type="file" name="bannerAdImage" id="bannerAdImage"开发者_开发问答/>
</p>
<p>
Title :<br />
<input type="text" name="bannerAdTitle" id="bannerAdTitle" />
</p>
<p>
Description :<br />
<textarea name="bannerAdDesc" id="bannerAdDesc" ></textarea>
</p>
<div id="button"><input type="button" value="VIEW" onclick="return upload()"/></div>
<input type="hidden" value="POST" />
</form>
And a Javascript
<div id="banAdT">
<script>
document.getElementById("bannerAdWeb").onchange = function() {
document.getElementById("banAdT").innerHTML = '<a href="'+this.value+'">';
}
</script>
<script>
document.getElementById("bannerAdTitle").onchange = function() {
var u = this.value;
document.getElementById("banAdT").innerHTML += u;
document.getElementById("banAdT").innerHTML += '</a>';
alert(document.getElementById("banAdT").innerHTML);
}
</script>
</div>
I am expecting the alert to show something like <a href="someurl">Some Title</a>
. But instead it shows <a href="someurl"></a>Some Title
! Please help..I can't find where I have done the wrong
Try something like this:
<script>
document.getElementById("bannerAdWeb").onchange = function() {
document.getElementById("banAdT").innerHTML = '<a id="bandAdTLink" href="'+this.value+'"></a>';
}
</script>
<script>
document.getElementById("bannerAdTitle").onchange = function() {
var u = this.value;
document.getElementById("bandAdTLink").innerHTML += u;
alert(document.getElementById("banAdT").innerHTML);
}
</script>
Solution explanation: you should never insert invalid HTML into the DOM via javascript.
You can't put invalid bits of HTML into the DOM and expect them to remain. The browser will error correct, e.g.
document.getElementById("banAdT").innerHTML = '<a href="'+this.value+'">';
That will be error corrected by the browser to an empty A element.
var u = this.value;
document.getElementById("banAdT").innerHTML += u;
That will likely append a u character after the A element.
document.getElementById("banAdT").innerHTML += '</a>';
No idea what the browser will make of that, it is literally creating:
<a href="..."></a>u</a>
so whatever happens is browser dependent.
Use DOM methods, don't mess around with innerHTML and string manipulation for non-trivial stuff. E.g. create the A element like:
var a = document.createElement('a');
a.href = this.value;
and later
a.appendChild(document.createTextNode('u'));
then append the a element something like:
document.getElementById("banAdT").apppendChild(a);
The problematic code is this:
document.getElementById("banAdT").innerHTML += u;
document.getElementById("banAdT").innerHTML += '</a>';
Those should be document.getElementById("bannerAdTitle").value
.
精彩评论