jQuery,我如何通过选中一个复选框来调用url [英] jQuery, how do I call a url by checking a checkbox

查看:76
本文介绍了jQuery,我如何通过选中一个复选框来调用url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

<span id="social">
    Facebook:
    <input id="id_connected_to_facebook" type="checkbox" name="connected_to_facebook">
    <br>
    Twitter:
    <input id="id_connected_to_twitter" type="checkbox" name="connected_to_twitter">
    <br>
</span>

和jQuery我想为所有4种可能的动作调用不同的URL(1:检查facebook,2:uncheck facebook,3:check twitter,4:uncheck twitter)。

and with jQuery I would like to call a different URL for all the 4 possible actions (1: check facebook, 2: uncheck facebook, 3: check twitter, 4: uncheck twitter).

我该怎么做?

推荐答案

我不确定你的目的是什么。如果要在单击复选框时重定向到页面,可以执行此操作

I am not sure what you are going for. If you want to redirect to a page on clicking on the check box you can do this

使用数据属性指定要在复选框元素中调用的URL

Specify what url you want to call in your checkbox element using data attribute

<input type="checkbox" data-target="http://www.facebook.com" />

脚本是

$(function(){
  $("input[type='checkbox']").change(function(){
  var item=$(this);    
  if(item.is(":checked"))
  {
    window.location.href= item.data("target")
  }    
 });
});

示例JsFiddle: http://jsfiddle.net/45aZ8/2/

Sample JsFiddle : http://jsfiddle.net/45aZ8/2/

编辑:如果你想在新窗口中打开它,使用 window.open 方法而不是更新当前网址

EDIT : If you want to open it in a new window, use window.open method instead of updating the current url

替换

window.location.href= item.data("target")

with

window.open(item.data("target")

http://www.w3schools.com/jsref/met_win_open.asp

编辑3 基于评论:如果你想在Checked状态下加载一个url并在uncheck上加载另一个url,你可以这样做

EDIT 3 : Based on comment : If you want to load one url on Checked state and load another url on uncheck, you can do like this

Give每个复选框有2个数据属性。一个用于检查状态,一个用于未选中状态

Give 2 data attributes for each checkbox. One for checked state and one for unchecked

Facebook<input type="checkbox" data-target="http://www.facebook.com" data-target-off="http://www.google.com"  /> <br/>
Twitter<input type="checkbox" data-target="http://www.twitter.com" data-target-off="http://www.asp.net"  /> <br/>

脚本是

$(function(){
  $("input[type='checkbox']").change(function(){
  var item=$(this);    
  if(item.is(":checked"))
  {
       window.open(item.data("target"))   
  }
  else
  {
      window.open(item.data("target-off"))   
  }        
 });
})

工作样本: http:// jsfiddle .net / 45aZ8 / 5 /

这篇关于jQuery,我如何通过选中一个复选框来调用url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆