问题描述
例如,我知道可以在 Javascript 中做一些事情,允许用户根据用户文本输入更新文本:
For instance, I know that it is possible to do something in Javascript that allows users to update text based on user text input:
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
document.getElementById('boldStuff2').innerHTML = userInput;
}
</script>
<p>Welcome to the site <b id='boldStuff2'>dude</b> </p>
<input type='text' id='userInput' value='Enter Text Here' />
<input type='button' onclick='changeText2()' value='Change Text'/>
在以下位置查看上面的代码:tizag.com/javascriptT/javascript-innerHTML.php
View the above code in action at: tizag.com/javascriptT/javascript-innerHTML.php
但是,我想知道是否可以对 url 链接执行类似的操作,而不是上面的代码.下面我放置了一个分步示例,说明我希望在用户输入文本时发生的情况:
However, instead of the above code, I would like to know if it's possible to do something similar for a url link. Below I've placed a step by step example of what I would like to happen upon the user inputing text:
文本字段中的用户输入:espn
User Input in Text Field:espn
用户点击按钮提交文本字段中的文本
User clicks button to submit text in text field
最终链接:http://www.google.com/search?q=espn
感谢您的帮助...顺便说一句...如果您看不出来我是个新手,请提供详细信息.
Thanks for your help...BTW...if you can't tell I'm a bit of a novice so detail is appreciated.
推荐答案
这是一个在您输入时更新的纯 JS 格式:
Here's one in plain JS that updates as you type:
<a id="reflectedlink" href="http://www.google.com/search">http://www.google.com/search</a>
<input id="searchterm"/>
<script type="text/javascript">
var link= document.getElementById('reflectedlink');
var input= document.getElementById('searchterm');
input.onchange=input.onkeyup= function() {
link.search= '?q='+encodeURIComponent(input.value);
link.firstChild.data= link.href;
};
</script>
注意:
没有内联事件处理程序属性(最好避免使用它们);
no inline event handler attributes (they are best avoided);
同时分配 keyup 和 change,以尝试在键盘更新发生时进行更新,并确保最终捕获所有其他更新;
assigning both keyup and change, to try to get keyboard updates as they happen and ensure that all other updates get caught eventually;
使用encodeURIComponent()
,以防搜索词中有任何非ASCII或URL特殊字符;
the use of encodeURIComponent()
, necessary in case the search term has any non-ASCII or URL-special characters in;
设置 Location(链接)对象的 search
属性,以避免再次写出整个 URL;
setting the search
property of a Location (link) object to avoid having to write out the whole URL again;
设置链接内 Text 节点的 data
以反映完整的 URL.不要从用户输入中设置 innerHTML
因为它可能包含 HTML 特殊字符,例如 &
和 <
在.
setting the data
of the Text node inside the link to reflect the full URL afterwards. Don't set innerHTML
from user input as it may have HTML-special characters like &
and <
in.
这篇关于是否可以根据用户文本输入更新 url 链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!