【问题标题】:call div on link click using ajax使用ajax在链接点击上调用div
【发布时间】:2013-07-26 14:49:14
【问题描述】:

我想在点击链接时打开 div。链接值包含数据行的 id。我正在使用 ajax 将数据发布到表单。

模板.html

<div id="authorisedreporter" {% if not registerform.errors %}style="display:none"{% endif %}>
 <form method="post" action="." id="reporter-form">
 {% csrf_token %}
 <table  width="100%">
 <tr>
   <td style="width:100px;">First name:</td><td>{{registerform.first_name}} </td>
 </tr>
 <tr>
    <td>Last name:</td><td>{{registerform.last_name}} </td>
 </tr>
     ''''''''''''''''
     some data here
     '''''''''''''''
 </table></form></div>

上面的div在页面加载时处于隐藏状态。我想在点击链接时打开div。

<td style="width:120px;"><a href="{{ list.0.id }}">{{list.0.first_name|title}} {{list.0.last_name}}</a></td>

需要帮助。

【问题讨论】:

  • 将事件监听器添加到 a 标签,然后从 div 更改样式值。

标签: javascript jquery html ajax django


【解决方案1】:

如果不是链接,请不要使用链接,在您的情况下,它更像是&lt;button&gt;

<td style="width:120px;"><button id="{{ list.0.id }}" class="js-openDiv">{{list.0.first_name|title}} {{list.0.last_name}}</button></td>

无论如何方法都是一样的,将class="js-openDiv"类添加到您的&lt;a&gt;&lt;button&gt;中,并将其用作jQuery中的选择器:

$('.js-openDiv').click(function () {
    var this_id = $(this).attr('id');  // the list ID
    // do something with the ID

    $('#authorisedreporter').show();
});

编辑:

如果你决定坚持使用&lt;a&gt; 标签:

<td style="width:120px;"><a id="{{ list.0.id }}" class="js-openDiv" href="#">{{list.0.first_name|title}} {{list.0.last_name}}</a></td>

jQuery 代码会有点不同:

$('.js-openDiv').click(function (e) {
    e.preventDefault();

    var this_id = $(this).attr('id');  // the list ID
    // do something with the ID

    $('#authorisedreporter').show();
});

希望对你有帮助

【讨论】:

  • +1,为您解答。点击链接后,应打开具有该 id 的 div,href="{{ list.0.id }}"> 标签中的值是一个 id ,所以我想知道如何将该 id 传递给 div,以便单击此链接时,div 应该打开链接中“id”的数据。谢谢
  • 您不应该使用href 来存储ID,将其更改为id,我认为您应该将整个&lt;a&gt; 更改为&lt;button&gt;,就像我的回答一样。我的回答已经包括如何获取该 ID。
  • 您可以为链接使用自定义属性。例如: 您可以通过 $(this).attr("someId") 在覆盖的内部访问点击功能
  • 我的 div 应该看起来像这样
  • 不,你的链接(你将点击的那个)应该有那个类,而不是你的&lt;div&gt;
【解决方案2】:

首先将href="#"href="javasctipt:void(0) 放在你的锚标签中,然后将id 放在锚标签的其他属性中。 那么脚本将是

$(document).ready(function(){
   $('a').click(function(){
      $('#authorisedreporter').show();
   });
});

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签