2

我有这个:

<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:取消选中 facebook,3:检查 twitter,4:取消选中 twitter)。

我该怎么做?

4

3 回答 3

8

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

使用 data 属性指定要在复选框元素中调用的 url

<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/

编辑:如果要在新窗口中打开它,请使用window.open方法而不是更新当前 url

代替

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

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

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

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

为每个复选框提供 2 个数据属性。一个用于选中状态,一个用于未选中

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/

于 2012-05-04T17:20:55.447 回答
0
$('input[type="checkbox"]').change(function() {
  if($(this).is(':checked')) {
     if($(this).attr('id') == 'connected_to_facebook') {
        // possibility: 1
     } else {
       // possibility: 3
     }
  } else {
    if($(this).attr('id') == 'connected_to_facebook') {
       // possibility: 2
     } else {
       // possibility: 4
     }
  }
});
于 2012-05-04T17:16:51.417 回答
0
$('#id_connected_to_facebook, #id_connected_to_twitter').click(function(){
   $.post('http://target.url', {this.id:this.checked});
});

现在您将进入 $_POST id_connected_to_facebook 或 id_connected_to_twitter 并且作为值它将是 1 或 0

于 2012-05-04T17:21:43.617 回答