问题
I'm self teaching myself CSS HTML and now Javascript.
The idea behind this small project of mine is to have an user enter an URL for an img, when the user hits a button the img should then be inserted into a new <div>
within the page.
I tried looking for hours at stackoverflow but i honestly don't understand how i can use other answers to my own code. most of the CSS and HTML code is already done, i just need help with the javascript part if its possible at all.
here is what i have so far: (sorry it's not much)
html code:
<form name="imgForm">
enter URL:
<input type="text" name="inputbox1" value="src" />
<input type="button" value="Get Feed" onclick="GetFeed()"/>
</form>
Javascript code:
<script type="text/javascript">
function GetFeed(imgForm){
var imgSrc = document.getElementById('src').value;
}
</script>
can anyone help me out? I dont know where to go from here.. at least give me some pointers how can i get the value from the txt box and add a new
<div><img src="user input from txt box should go here"/></div>
for every time an unser inserts and new URL for an img?
Thanks in advanced.
回答1:
I think according to your need how can i get the value from the txt box and add a new <div><img src="user input from txt box should go here"/></div>
you need this
HTML
<form>
<input type="text" id="txt">
<input id="btn" type="button" value="Get Image" onclick="getImg();" />
</form>
<div id="images"></div>
JS (goes inside your head tags)
function getImg(){
var url=document.getElementById('txt').value;
var div=document.createElement('div');
var img=document.createElement('img');
img.src=url;
div.appendChild(img);
document.getElementById('images').appendChild(div);
return false;
}
Here is an example.
回答2:
You should add an id
attribute to your <input>
:
<input type="text" name="inputbox1" id="box1" value="src" />
...then, adjust your code:
var imgSrc = document.getElementById('box1').value;
Once you have the source, you can get back an object for the img
tag, and set its properties using the value from the text box. The img
object's properties are defined by the Document Object Model:
http://www.w3schools.com/jsref/dom_obj_image.asp
回答3:
Something like this will create a div with an image element that has a src equal to the text in the input box. It then appends the div to end of the page.
<html>
<head>
<script type="text/javascript">
function GetFeed(form){
var imgSrc = form.elements["inputbox1"].value;
var imgDiv = document.createElement('div');
imgDiv.innerHTML = "<img src=\"" + imgSrc + "\"/>"
document.body.appendChild(imgDiv);
}
</script>
</head>
<body>
<form name="imgForm">
enter URL:
<input type="text" name="inputbox1" value="src" />
<input type="button" value="Get Feed" onclick="GetFeed(this.form)"/>
</form>
</body>
</html>
来源:https://stackoverflow.com/questions/9881477/get-img-src-from-input-box-into-a-div