gpt4 book ai didi

javascript - 改进 View 文件中的 JavaScript 代码

转载 作者:数据小太阳 更新时间:2023-10-29 08:10:28 24 4
gpt4 key购买 nike

我正在使用 Ruby on Rails 3.0.7,我想知道如何重构DRY(不要重复自己)和改进 我的 View 文件中的以下代码:

<% articles.each do |article| %>

<div>
<%= link_to 'add', '#', :id => "create_#{article.id}" %>
</div>

<script type="text/javascript">
# Code - Block 1
$jQ('#create_<%= article.id %>').live('click', function(event) {
$jQ.ajax({
type: "POST",
url: "<%= article_url(@article) %>/create",
data: "article_id=<%= @article.id %>",
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n\n' + jqXHR.responseText);
},
success: function(data, textStatus, jqXHR) {
$jQ('#create_<%= article.id %>').replaceWith('<%= escape_javascript("added") + (link_to 'remove', '#', :id => "destroy_#{article.id}") %>')
}
});
});

# Code - Block 2
$jQ('#destroy_<%= .id %>').live('click', function(event) {
$jQ.ajax({
type: "POST",
url: "<%= article_url(@article) %>/destroy",
data: "article_id=<%= @article.id %>,
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n\n' + jqXHR.responseText);
},
success: function(data, textStatus, jqXHR) {
$jQ('#destroy_<%= article.id %>').replaceWith('<%= escape_javascript("removed") + (link_to 'add', '#', :id => "create_#{article.id}") %>')
}
});
});
</script>

<% end %>

注意:

  • each 语句!
  • 上面的“两个代码块”几乎相等。

最佳答案

  • 将主体放在一个字符串中
  • 有一个数组数组用于两次迭代(一次使用 ['create','added','remove',destroy'],另一个使用 ['destroy','删除','添加','创建'])
  • 循环两次 (0..1),为找到文本的那些槽插入数组值
    • 第一遍:数组[0][0]、数组[0][0]、数组[0][0]、数组[0][1]、数组[0][2]、数组[0][3]
    • 第二遍:数组[1][0]、数组[1][0]、数组[1][0]、数组[1][1]、数组[1][2]、数组[1][3]

注意:我的 Ruby 生锈了,所以这是伪代码。
示例(查找 ary[i][n]):

ary = [['create','added','remove',destroy'],
['destroy','removed','add','create']]

for i in (0..1)
$jQ('#**ary[i][0]_<%= article.id %>').live('click', function(event) {
$jQ.ajax({
type: "POST",
url: "<%= article_url(@article) %>/ary[i][0]",
data: "article_id=<%= @article.id %>",
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n\n' + jqXHR.responseText);
},
success: function(data, textStatus, jqXHR) {
$jQ('#ary[i][0]_<%= article.id %>')
.replaceWith('<%= escape_javascript("ary[i][1]") + (link_to 'ary[i][2]', '#', :id => "ary[i][3]_#{article.id}") %>')
}
});
});
end

关于javascript - 改进 View 文件中的 JavaScript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6603713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com