使用JavaScript实现点击服务条款链接触发条款弹窗
实现方法
不需要额外编写新的函数逻辑,直接修改目标<a>标签的属性即可完成需求,操作步骤如下:
- 把
<a>标签的空href属性替换为javascript:void(0),阻止点击链接时默认触发的页面跳转/刷新行为 - 给
<a>标签添加onclick事件绑定,直接复用已写好的myTermsandConditions()函数 - 按需求移除原有的T&C按钮元素即可
核心代码修改
原链接代码:
<a href="" >Terms and Conditions</a>
修改后代码:
<a href="javascript:void(0)" onclick="myTermsandConditions()">Terms and Conditions</a>
完整可运行代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> function myTermsandConditions(){ var myWindow = window.open("","MsgWindow","width=200,height=200"); myWindow.document.write("<p>This is Terms and Conditions Window. Please go through all the Terms and Conditions for your references.</p>") } </script> </head> <body> <label class="sign_agree"> <span id="signup-termservice" class="unchecked"> </span>I agree to the <a href="javascript:void(0)" onclick="myTermsandConditions()">Terms and Conditions</a> . </label> </body> </html>
补充说明:如果不想用
javascript:void(0)写法,也可以在onclick事件中阻止默认行为,写法为onclick="myTermsandConditions(); return false;",这种写法下即使href留空也不会触发页面跳转,两种写法效果完全一致。
内容的提问来源于stack exchange,提问作者Mahi
相关产品推荐
相关产品推荐

