gpt4 book ai didi

javascript - 使用在不同页面上单击的链接更改表单选择字段

转载 作者:行者123 更新时间:2023-11-28 01:42:27 25 4
gpt4 key购买 nike

我有一个服务页面,该页面链接到带有表单的约会页面,我希望所选的服务在下拉列表中更改为所选的正确服务。

我能找到的类似问题的唯一解决方案是下面的答案。但是,当表单位于单独的页面上时,它似乎不起作用。当我将表单复制到同一页面并在页面底部使用 anchor 时,它会更改字段,但是当使用指向其他页面的链接时,它不会。我假设这是因为它在另一个页面上,但是我找不到关于这种情况的太多信息。

我已经包括了我的代码的副本,我相信我已经包括了每个部分的相关片段。

Change dropdown option with jQuery/Javascript on link click


在两个页面头部声明脚本:

<script src="Scripts/jquery-1.11.1.js"> </script>
<script src="Scripts/jquery-ui-1.11.0.custom/jquery-ui.js"></script>
<script src="myscript.js"></script>

来自服务页面上 HTML 链接的代码:

<a href="BookAppointment.html" data-select="Bronze">

来自 JS 的代码:

var $select = $('#package');
$('a[href="BookAppointment.html"]').click(function () {
$select.val( $(this).data('select') );
});

来自预约表的代码(更多选项未列出):

<select name="package" id="package" >         
<option value="Exterior Wash">Exterior Wash</option>
<option value="Bronze">Bronze</option>
<!-- more options -->
</select>

在此先感谢您提供的任何帮助。

最佳答案

实际上,如果您将所有元素嵌入到同一页面中,您的代码就可以工作,尤其是 <select>元素,因为你的 JS 代码是在页面范围内执行的。因此,您可以在点击 a 时更改选择值href 元素。

为了拥有你的data-select BookAppointment.html 页面中可用的值,其值应转发到该页面。所以总结一下,当你点击 a services.html 页面中的 href 元素,data-select值通过 JavaScript 处理并封装为查询参数,然后重定向到 BookAppointment.html 页面。

  • 现在假设您的 services.html 页面如下(注意新的 service-script.js):
<head>
<script src="Scripts/jquery-1.11.1.js"> </script>
<script src="Scripts/jquery-ui-1.11.0.custom/jquery-ui.js"></script>
<script src="service-script.js"></script>
</head>
<body>
<a href="BookAppointment.html" data-select="Bronze">
</body>
  • service-script.js 文件中,您将捕获 a 上的用户点击事件。 href,然后检索 data-select 值(就像您之前所做的那样)。新部分是在您将重定向到的 html 引用中引入该值:
$(document).ready(function() {
$('a[href="BookAppointment.html"]').click(function (e) {
e.preventDefault();
var data = $(this).data('select');
window.location = $(this).attr('href') + '?selectParam=' + escape(data);
});
});
  • 现在你必须移动你的<select>阻止到 BookAppointment.html 页面(注意新的 book-appointment-script.js):
<head>
<script src="Scripts/jquery-1.11.1.js"> </script>
<script src="Scripts/jquery-ui-1.11.0.custom/jquery-ui.js"></script>
<script src="book-appointment-script.js"></script>
</head>
<body>
<select name="package" id="package" >
<option value="Exterior Wash">Exterior Wash</option>
<option value="Bronze">Bronze</option>
<!-- more options -->
</select>
</body>
  • book-appointment-script.js 文件中,您将捕获 selectParam 查询参数并根据它更新选择选项:
$(document).ready(function () {
var selectData = unescape(window.location.search.substring(1).split('=')[1]);
var $select = $('#package');
$select.val( selectData );
});

您可能需要转义和取消转义 html 特殊字符,因为这只是一个简单的示例

关于javascript - 使用在不同页面上单击的链接更改表单选择字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25104137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com