我在解决上一篇文章时遇到了麻烦。我只有一个需要jQuery
的解决方案,但我想改用JavaScript
。
真的需要帮助。
上一篇文章(供参考):HTML - How To Display & Direct Selected Values From Drop Down Menu To A New HTML Page
这是第一个jquery代码。
<input type="submit" id="btngo" value="Go" />
<script type="text/javascript">
$(function() {
$("#btngo").bind("click", function() {
var url = "Page2.htm?foodbeverage=" + encodeURIComponent($("#foodbeverage").val()) + "&status=" + encodeURIComponent($("#status").val());
window.location.href = url;
});
});
</script>
&#13;
这是第二个jquery代码。
< script type = "text/javascript" >
var queryString = new Array();
$(function() {
if (queryString["foodbeverage"] != null && queryString["status"] != null) {
var data = "<b>Food Beverages:</b> " + queryString["foodbeverage"] + " <b>Dine Takeaway:</b> " + queryString["status"];
$("#showdata").html(data);
}
}); <
/script>
&#13;
答案 0 :(得分:1)
我已将第一个代码段转换为本机JS等效代码。我没有将状态添加到URL,它与获取食物饮料的情况更相似。
(function() {
/**
* Handles the click of the submit button.
*/
function onSubmitClicked(event) {
// Get the input element from the DOM.
var beverage = document.getElementById('foodbeverage'),
// Get the value from the element.
beverageValue = beverage.value,
// Construct the URL.
url = 'Page2.html?foodbeverage=' + encodeURIComponent(beverageValue) + '&status=test';
// Instead of going to the URL, log it to the console.
console.log('goto to URL: ', url);
}
// Get the button from the DOM.
var submitButton = document.getElementById('btngo');
// Add an event listener for the click event.
submitButton.addEventListener('click', onSubmitClicked);
})();
&#13;
<label>
Beverage:
<input type="text" id="foodbeverage"/>
</label>
<input type="submit" id ="btngo" value="Go" />
&#13;
答案 1 :(得分:0)
对于第二个代码段,请在表单/页面中添加div
。下面的JS函数将使用传递的参数更新窗口onload上的div
值。请注意,div
仅在存在两个查询字符串参数时才会更新。
<div id="showdata"></div>
<script type="text/javascript">
window.onload = passParameters;
//Function to update "showdata" div with URL Querystring parameter values
function passParameters() {
var foodbeverage = getParameterByName("foodbeverage");
var status = getParameterByName("status");
if (foodbeverage != null && status != null) {
var data = "<b>Food Beverages:</b> " + foodbeverage + " <b>Dine Takeaway:</b> " + status;
document.getElementById("showdata").innerHTML = data;
}
}
//Get URL parameter value
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>