从html’value’属性中检索值

如何检索名为“value”的html元素属性中定义的实际值?

在用户注册之前,我正在设置一个会话变量,其值应为“发布者”或“读者”,具体取决于他们点击的div。 此会话值将在用户创建时使用。

   

client.js(尝试将会话变量设置为’reader’或’publisher’,具体取决于他们点击的两个div)

 Template.authJoinType.events({ 'click div.join-type-inner': function(e, tmpl) { var userType = $(e.target).find('#userTypeSelect').val(); Session.set('userType', userType); var selectedUserType = Session.get('userType'); console.log(selectedUserType); // this is printing out 'undefined' } }); 

救命? 我是否以不正确的div为目标?

更改:

 var userType = $(e.target).find('#userTypeSelect').val(); 

至:

 var userType = $(e.target).attr("value"); 

您必须为HTML中的每个元素使用唯一id ,但您已为多个元素使用了id="userTypeSelect" ,因此请更改它。

您可以使用.attr('value')来读取div的value属性。 这里.val()不会工作,因为div没有这样的值,但你可以拥有名称value属性。

并修改您的脚本,如下所示

 Template.authJoinType.events({ 'click div.join-type-inner': function(e, tmpl) { //use 'this' reference to read value attribute, //here 'this' is the clicked element var userType = $(this).attr('value'); Session.set('userType', userType); var selectedUserType = Session.get('userType'); console.log(selectedUserType); // this is printing out 'undefined' } }); 

您的代码有几个问题:

  • 您有重复的id属性,这些属性无效并且会导致JS中出现问题 – 正如您所发现的那样。
  • value属性对div元素无效。 您可以改为使用data-*属性在元素中存储自定义数据。
  • div元素不能放在内联元素内,将它们更改为span
  • 鉴于您定义的click事件位于.join-type-inner元素上,您不需要执行find()因为e.target是您需要的元素。

试试这个:

  
 Template.authJoinType.events({ 'click div.join-type-inner': function(e, tmpl) { var userType = $(e.target).data('value'); Session.set('userType', userType); var selectedUserType = Session.get('userType'); console.log(selectedUserType); // should say 'reader' || 'publisher' depending on clicked link } }); 

这适用于任何引用该post的人。 得到的工作答案如下所示。 请为此答案投票给sanki。 我只是重新铺设信息。

HTML:

  

client.js

 Template.authJoinType.events({ 'click div.join-type-inner': function(e, tmpl) { var userType = $(e.target).attr("value"); Session.set('userType', userType); var selectedUserType = Session.get('userType'); console.log(selectedUserType); } });