2015-12-02 65 views
0

我正在测试获取文本输入并将结果打印在下面的div中。但是,我看不到它的工作。jQuery/Javascript - 获取文本输入字段的值,并显示在div

如果输入字段的“占位符”变成了“值”,它莫名其妙地起作用。我可能会感到疲倦,并且错过了一些明显的东西,但是我不能为了我的生活而弄清楚什么是错的。

//Tested and didn't work 
 
//var URL = document.getElementById("download")[0].value; 
 
//var URL = document.getElementsByName("download")[0].value; 
 

 
var URL = $('#download').val(); 
 

 
function downloadURL() { 
 
    //Print to div 
 
    document.getElementById("output").innerHTML = URL; 
 
    //Test, just in case innerHTML wasn't working 
 
    alert(URL); 
 
}
<p><input type="text" name="download" id="download" placeholder="Download URL"></p> 
 
<button onclick="downloadURL()">Test</button> 
 
<div id="output"></div>

+0

您必须在函数内部获取已更改的值,现在您在函数运行之前获取一次值,并将其存储在一个变量中,然后一次又一次地使用相同的值,例如该变量不在函数外部时更新。 – adeneo

回答

3

只是一个小变化,你当你点击按钮,获取价值,所以先保存到该领域的引用,然后在需要时获得价值

var URL = $('#download'); 

function downloadURL(){ 
    //Print to div 
    document.getElementById("output").innerHTML = URL.val(); 
    // alert(URL.val()); 
} 
+0

这适用于div,虽然警报显示[对象对象] ...虽然我想这并不重要 – Jordan

+0

更改警报(URL)以提醒(URL.val())..我忘了更改 –

0

我建议你坚持jQuery。让jQuery以不显眼的方式运行,而不是依赖于附加到button的内联事件处理程序。

<p> <input type="text" name="download" id="download" placeholder="Download URL"></p> 
<button>Test</button> //remove the inline click handler      
<div id="output"></div> 

$('button').on('click', function() { 
    var url = $('#download').val(); 
    $('#output').text(url); //or append(), or html(). See the documentation for further information 
}); 
0

对代码进行少量修改,使其可以与“Unobtrusive Javascript”对齐。

HTML

<p> 
    <input type="text" name="download" id="download" placeholder="Download URL"> 
</p> 
<button id="btnDownloadUrl">Test</button>       
<div id="output"></div> 

jQuery的

$(function(){ 
    $("#btnDownloadUrl").bind("click", function(){ 
     var downloadUrl = $("#download").val(); 
     $("#output").html(downloadUrl); 
    }); 
}); 
+0

确保命名该回调函数,或者最好在外部定义它并将其名称作为回调参数传递。 –

1

如果你想要去的jQuery ...

var URL = $('#download'); 

function downloadURL() { 
    $("#output").html(URL.val()); 
} 

...或者普通的JavaScript

var URL = document.getElementById("download") ; 

function downloadURL() { 
    document.getElementById("output").innerHTML = URL.value; 
} 
相关问题