[英]How do I append a url typed into a input text field to an anchor then follow it when anchor is clicked?
I want to have a text field where people can type in a value. 我想要一个文本字段,人们可以在其中输入值。 Then I want to have a href open a url with the text field appended to the end.
然后我想要一个href打开一个URL,文本字段附加到末尾。
So if the text field says "elephant" then when they click the link, a page will open with at example.com/elephant. 因此,如果文本字段显示“elephant”,那么当他们单击链接时,将在example.com/elephant上打开一个页面。
I think javascript would be the easiest way to accomplish this but I just don't know how. 我认为javascript将是实现这一目标的最简单方法,但我只是不知道如何。
I'm assuming that you have some HTML like the following and want to append the contents of the appendUrl input field to the url in the anchor tag when the anchor tag is clicked. 我假设您有一些像下面这样的HTML,并且想要在单击锚标记时将appendUrl输入字段的内容附加到锚标记中的url。
<a href="/base/url" id="baseUrl">Link Text</a>
<input type="text" id="appendUrl" />
Then, using jQuery, it would look something like: 然后,使用jQuery,它看起来像:
$(function() {
$('#baseUrl').click( function() {
window.location = $(this).attr('href') + '/' + $('#appendUrl').val();
return false;
});
});
The basic idea is to extract the value of the input and append it to the url in the href. 基本思想是提取输入的值并将其附加到href中的url。 Use the value so constructed to set the location of the current window.
使用如此构造的值来设置当前窗口的位置。 I return false in the click handler to prevent the default action (the base url alone) from being taken.
我在单击处理程序中返回false以防止执行默认操作(仅基本URL)。
<input type="text" id="suffix" />
<a href="http://example.com/" onclick="document.location.href = $(this).attr('href')+$('#suffix').val(); return false;">click me</a>
Here is a library agnostic version of what you want: 这是您想要的库不可知版本:
Your HTML: 你的HTML:
<input type="text" name="url_param" id="url_param" />
<input type="button" onclick="prepare_link();" value="Do it!" />
<a href="http://whatever.com" id="target_link">Click Your New Link!</a>
Your Javascript: 你的Javascript:
<script type="text/javascript">
function prepare_link() {
var url_param = document.getElementById('url_param');
var target_link = document.getElementById('target_link');
if ( ! url_param.value ) {
return false;
}
target_link.href = target_link.href + '/' + escape(url_param.value);
}
</script>
This is not the cleanest way to write the code and not how I would do it, but I tried to make it as simple as possible in the most generic way so that you'd be able to understand the code. 这不是编写代码最简洁的方法,而不是我如何编写代码,但我尝试以最通用的方式使其尽可能简单,以便您能够理解代码。
HTML HTML
<a href="/base/url" id="stndrUrl">Sample text</a><input type="text" id="appendUrl" name=""/>
JQUERY JQUERY
$(document).ready(function(){
$('#stndrUrl').click( function() {
window.location = $(this).attr('href') + '/' + $('#appendUrl').val();
return false;
});
}); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.