如何将select tag中的选定值作为查询字符串传递给锚标记,以便可以在其他php页面上访问? 我想做这样的事情:
<select name="category">
<option></option>
</select>
<a href="category.php?selected='category.value'></a>
这样做的正确方法是什么?我使用的是http://www.ibm.com/developerworks/library/os-osgiblueprint/和html。
答案 0 :(得分:0)
这样的东西?
$('[name="category"]').change(function(){
var href = $(this).val();
$('.linkhere').attr('href','category.php?selected='+href);
});
答案 1 :(得分:0)
使用纯JavaScript,我建议:
// a named function to handle the change event:
function addValueToURL() {
// this (in this demo the <select> element) passed
// automatically from the addEventListener() method;
// here we encode the value of the <select> using
// encodeURIComponent() to ensure the value will
// be made up of URL-safe/valid characters:
var value = encodeURIComponent(this.value),
// getting a reference to the <a> element that you
// want to update:
anchor = this.nextElementSibling;
// the HTMLAnchorElement's search property,
// the portion of a URL following the '?'
// is here set to the string 'category='
// followed by the URI-encoded value from
// the <select>:
anchor.search = 'category=' + value;
}
// getting a reference to the first element that matches
// the CSS selector, selecting a <select> element with a
// name-attribute equal to 'category':
var select = document.querySelector('select[name=category]'),
// creating a new Event (with the same name as an
// existing event) in order to trigger that event
// when the page loads:
changeEvent = new Event('change');
// binding the function as the event-handler
// for the 'change' event:
select.addEventListener('change', addValueToURL);
// triggering the 'change' event:
select.dispatchEvent(changeEvent);
使用CSS:
a::before {
content: attr(href);
}
CSS完全与功能无关,只是让您在<a>
元素的网址中看到更改。
function addValueToURL(event) {
var value = encodeURIComponent(this.value),
anchor = this.nextElementSibling;
anchor.search = 'category=' + value;
}
var select = document.querySelector('select[name=category]'),
changeEvent = new Event('change');
select.addEventListener('change', addValueToURL);
select.dispatchEvent(changeEvent);
a::before {
content: attr(href);
}
<select name="category">
<option value="option1">Option One</option>
<option value="option2">Option Two</option>
<option value="option3">Option Three</option>
<option value="option4">Option Four</option>
</select>
<a href="http://exampledomain.com"></a>
我们可以在简单的html锚标签中执行此操作,而无需使用[JavaScript] ...
不,至少目前不是
...或[jQuery]
当然,是的; jQuery是永远的一个要求,它只是一个JavaScript库,可以更容易地编写简单的跨浏览器兼容代码(该库透明地处理跨浏览器问题,因此作者没有担心它。)
参考文献: