我正在尝试从变量HTML元素中检索数据。单击时,将检索<span>
元素的id,我希望能够动态$([dynamic id])
选择该元素并请求存储在data属性中的数据。
我的jQuery看起来像这样:
$( document ).ready( function() {
$( ".checkmark" ).on( "click", ( event ) => {
let checkBoxId = "#" + event.target.id, // #checkBox1
checkBoxData = event.target.id + "-value", // checkBox1-value
checkBoxValue = $( checkBoxId ).data( checkBoxData ); // undefined
} );
} );
目标HTML元素如下所示:
<span class="checkmark" id="checkBox1" data-checkBox1-value=-155></span>
let checkBoxValue的值是未定义的,我无法弄清楚原因。 非常感谢帮助。
答案 0 :(得分:1)
答案 1 :(得分:1)
您似乎遇到了新()=>{}
语法的范围问题。
因此,您需要使用this
将{self:this}
绑定到函数事件处理程序。如果您不想这样做,则可以使用旧的function(){}
语法。
$( document ).ready( function() {
$( ".checkmark" ).on( "click", {self:this}, ( event ) => {
var checkBoxValue = $(this).data("checkbox1-value")
alert(checkBoxValue);
} );
} );
正如@Erwin所提到的,在data-
属性名称中仅使用小写:
<span class="checkmark" id="checkbox1" data-checkbox1-value="-155"></span>
答案 2 :(得分:1)
import * as types from '../actions/types';
var _ = require('lodash');
const INITIAL_STATE = {
data: {},
loading: false,
error: '',
cartData: {},
};
export default (state=INITIAL_STATE, action) => {
switch (action.type) {
case types.MENULIST_REQUEST_START:
return { ...state, loading:true, error: '' };
case types.MENULIST_SUCCESS:
const newItems = _.mapKeys(array, 'name')
return { ...state, data: newItems , loading:false, error: 'Success' };
case types.UPDATE_ITEM:
return { ...state, [cartData.name]: action.payload }
case types.DELETE_ITEM:
return _.omit(state, [cartData.name]: action.payload)
case types.MENULIST_FAILED:
return { ...state, data: {}, loading:false, error: 'Request failed' };
default:
return state;
}
}
变量是不必要的,因为您可以使用checkBoxId
关键字,因为它是您正在使用的当前元素。
this
答案 3 :(得分:0)
它返回undefined
因为声明不正确。 data-
之后的部分应为小写。在你的情况下,它必须是
<span class="checkmark" id="checkbox1" data-checkbox1-value=-155></span>
让.data()
工作。
答案 4 :(得分:0)
此代码适合我尝试;)
$( document ).ready( function() {
$( ".checkmark" ).on( "click", function() {
var checkBoxId = "#" + $(this).attr('id');
var checkBoxData = $(this).attr('id') + "-value";
$( this ).attr('data-'+ checkBoxData, 155 );
} );
});