使用jQuery click()方法未定义$(this).data(value)的值 [英] Undefined value of $(this).data(value) with jQuery click() method
问题描述
我的Rails 5应用程序,我正在构建一个动态菜单,根据用户的位置将用户路由到网站的特定部分。当他们点击主页上的菜单项时,会显示一个模式,供他们选择我们提供的四个位置之一。然后,使用click方法的函数应该获取data-attribute并将其插入到url路径中以重定向它们。我似乎无法获得数据属性通过,即使硬编码 - 我只是得到一个未定义的控制台。
我不包括模态代码因为这不是问题;它会像控制台一样打开并在路径中插入/ undefined / undefined /。我的问题是只有在这个
数据值。
_sidebar.html.erb
< div id =ss_menu>
<%@ cat.each do | c | %GT;
< div class =ss_button><%= c.name%>< / div>
< div class =ss_content>
< ul>
<%c.subcategories.each do | s | %GT;
< li>
< a href =#
data-id =<%= s.id%>
data-category =<%= c.slug%>
data-subcategory =<%= s.slug%>
data-toggle =modal
data-target =。mlc-modal><%= s.name%>< / a>
< / li>
<%end%>
< / ul>
< / div>
<%end%>
< / div>
脚本
< script type =text / javascriptcharset =utf-8>
$(document).on(click,.ss_button,function(){
var id = $(this).data('id');
var category = $(id).data('category');
var subcategory = $(id).data('subcategory');
console.log(id);
console.log类别);
console.log(subcategory);
$('。modal-content a')。attr('href',function(){
return this.href + category + '/'+子类别;
});
});
< / script>
var id = $(this).data('id');
这里 $(this)
指< div class =ss_button>
其中没有 data-id
属性。
所以它会一直到(输出)为 undefined
。
Im my Rails 5 app, I am building a dynamic menu to route users to a particular part of the site based on their location. When they click on a menu item from the home page a modal is show for them to choose one of four locations we deliver to. A function with the click method then should grab the data- attribute and insert it into the url path to redirect them. I cannot seem to get the data attribute to pass through even if hard coded - I just get an undefined in the console.
I am not including the modal code here because it is not the issue; it opens and inserts /undefined/undefined/ in the path just like the console. My issue is only in getting this
data value.
_sidebar.html.erb
<div id="ss_menu">
<% @cat.each do |c| %>
<div class="ss_button"><%= c.name %></div>
<div class="ss_content">
<ul>
<% c.subcategories.each do |s| %>
<li>
<a href="#"
data-id="<%= s.id %>"
data-category="<%= c.slug %>"
data-subcategory="<%= s.slug %>"
data-toggle="modal"
data-target=".mlc-modal"><%= s.name %></a>
</li>
<% end %>
</ul>
</div>
<% end %>
</div>
script
<script type="text/javascript" charset="utf-8">
$(document).on("click", ".ss_button", function () {
var id = $(this).data('id');
var category = $(id).data('category');
var subcategory = $(id).data('subcategory');
console.log(id);
console.log(category);
console.log(subcategory);
$('.modal-content a').attr('href', function () {
return this.href + category + '/' + subcategory;
});
});
</script>
var id = $(this).data('id');
Here $(this)
refers to <div class="ss_button">
which have no data-id
attribute.
So it will always comes(outputs) as undefined
.
这篇关于使用jQuery click()方法未定义$(this).data(value)的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!