1

我在我的应用程序中连接到 Foursquare API。用户可以键入一个框来开始搜索场地,或者他们可以单击两个场地链接之一以用这两个场地之一填充相同的选择框。我无法让用户单击两个场所之一。这是我的代码:

JS:

function venueFormatSelection(venue) {

  if ( venue.name && venue.location.address ) {
    // if a user starts typing into a box, venue.name and venue.address values will  pop up for them to select from. OR in the 'else' case, they can click one of either two links
  else {

    $("#bigdrop_set").click(function () {
      return $('#bigdrop_set').attr('venue_name')
    })

    $("#bigdrop_set_2").click(function () { 
      return $('#bigdrop_set_2').attr('venue_name_2')
    })

  }
}

HTML:

<span class="which_venue" id="bigdrop_set" venue_name='foo' venue_data='FOO'><%= link_to(FOOOOO) %></span>

<span class="which_venue" id="bigdrop_set_2" venue_name_2='bar' venue_data_2='BAR'><%= link_to(BARRRR) %></span>

出于某种原因,“单击以填充”JS 仅在没有 .click 功能的情况下仅包含一个“返回”行时才有效:

return $('#bigdrop_set').attr('venue_name')

我的“else”语句中的代码有什么问题?谢谢!

4

3 回答 3

1
 $(".bigdrop_set").click(function () {
  return $('#bigdrop_set').attr('venue_name')
  })

应该:

$("#bigdrop_set").click(function () {
  return $('#bigdrop_set').attr('venue_name')
 })

当您选择 ID 为 bigdrop_set 的元素而不是类 bigdrop_set 的元素时。ID 应该是唯一的,在您的代码中,您有重复的 bigdrop_set ID,应该更改。

另外我建议在函数上绑定点击元素$(document).ready(),而不是在venueFormatSelection函数中。

从 click 函数返回值也没有多大意义。要么直接在函数中操作值,要么将其放在另一个函数本身中,而不是放在click事件中。

例如:

function alertVenue(venue) {
   alert(venue)
}

$("#bigdrop_set").click(function () {
   var venue = $('#bigdrop_set').attr('venue_name')
   alertVenue(venue);
})
于 2013-01-22T14:54:15.753 回答
0

你有类似的东西

$(".bigdrop_set").click(function () {
  return $('#bigdrop_set').attr('venue_name')
})

您真的是指 css 类选择器.bigdrop_set,然后是 id 选择器#bigdrop_set

于 2013-01-22T14:55:44.643 回答
0

我通过使用全局变量找到了解决方法。怀疑这是最干净的方法,但它现在正在工作:

$("#bigdrop_set").click(function () { 
  window.clickVenue = $('#bigdrop_set').attr('venue_name');
  $(".bigdrop").select2("val", $('#bigdrop_set').attr('venue_data'));
});

$("#bigdrop_set_2").click(function () { 
  window.clickVenue = $('#bigdrop_set_2').attr('venue_name_2');
  $(".bigdrop").select2("val", $('#bigdrop_set_2').attr('venue_data_2'));
});

function venueFormatSelection(venue) {

  if (venue.name && venue.location.address) {
    var imageSource = venue.categories[0].icon.prefix.slice(0, -1) + venue.categories[0].icon.suffix;
    return "<img src='" + imageSource + "' height='20' width='20' />" + "   " + venue.name + " (" + venue.location.address + ")";
  }
  else {
    return window.clickVenue;
  }
}
于 2013-01-22T17:08:57.317 回答