【问题标题】:CoffeeScript: Line-Through on LI after Checkbox is checkedCoffeeScript:选中复选框后,LI 上的 Line-Through
【发布时间】:2013-03-04 12:24:25
【问题描述】:

我在 Rails 上的应用程序中使用 CoffeeScript,现在在更改复选框后,我调用 jquery 函数以使用 ajax 更新其在数据库中的值,但我还想在复选框中添加一行被选中。

HTML:

    <ul>
       <li class="side-bar-element">
           <input class="task" id="1" name="1" type="checkbox" value="Element 1"/>
           Element 1
       </li>
       <li class="side-bar-element">
           <input class="task" id="2" name="2" type="checkbox" value="Element 2"/>
           Element 2
       </li> 
       <li class="side-bar-element">
           <input class="task" id="3" name="3" type="checkbox" value="Element 3"/>
           Element 3
       </li> 
       <li class="side-bar-element">
           <input class="task" id="4" name="4" type="checkbox" value="Element 4"/>
           Element 4
       </li>  
    </ul>

CoffeeScript:

$(".task").live "change", ->
  id = $(this).attr("id")
  isChecked = $(this).attr("checked")
  $.ajax
    url: "/update"
    type: "post"
    data: { id }

    success: ->
      alert "Updated Succesfully."
      if(isChecked)
        alert "For Testing: Is Checked."
        $(this).closest('li').css "text-decoration", "line-through"

    error: ->
      alert "Changes were not saved."

我不明白为什么“已检查”警报可以正常工作,但它从不更新 CSS。我也尝试使用 parent()、prev() 但没有运气。任何帮助将非常感激。谢谢。

【问题讨论】:

    标签: jquery html coffeescript


    【解决方案1】:

    成功回调里面的this不是你想的那样。

    所有回调中的 this 引用是设置中传递给 $.ajax 的 context 选项中的对象;如果未指定上下文,则这是对 Ajax 设置本身的引用。

    使用

    $.ajax
        context: this,
        url: "/update"
        type: "post"
        data: { id }
        //.....
    

    $.ajax 还有很多其他选项http://api.jquery.com/jQuery.ajax/

    【讨论】:

    • 很好的答案。不知道context:
    • 好答案,在+1之前不知道这个
    • 可以添加文档链接
    • 感谢您的帮助...我也不知道上下文。
    猜你喜欢
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 2017-07-31
    • 1970-01-01
    相关资源
    最近更新 更多