$(this).attr('xxx') undefined

错误代码

 function bindBtnDeleteEvent() {
            $('.btn-delete').click(()=>{
                    $('#deleteModal').modal('show');
                    // 获取当前行的id 并赋值给全局变量
                    DELETE_ID = $(this).attr('uid');
                    console.log(DELETE_ID);
                }
            )
        }

修改后的代码

 function bindBtnDeleteEvent() {
            $('.btn-delete').click(function () {
                    {#alert('点击了删除');#}
                    $('#deleteModal').modal('show');

                    // 获取当前行的id 并赋值给全局变量
                    DELETE_ID = $(this).attr('uid');
                    console.log(DELETE_ID);
                }
            )
        }

attr方法一直读出是undefined 发现是因为用了箭头函数 换成function函数就解决了
当元素是动态生成的时候,如果想给该元素绑定事件,我们可以使用委托
注意!委托中不能使用箭头函数,否则会输出undefined

jquery attr方法

$(this).attr(key); 获取节点属性名的值,相当于getAttribute(key)方法

$(this).attr(key, value); 设置节点属性的值,相当于setAttribute(key,value)方法


$(this).val();获取某个元素节点的value值,相当于$(this).attr("value");

$(this).val(value);设置某个元素节点的value值,相当于$(this).attr("value",value);
posted @ 2022-04-19 23:56  晨落  阅读(471)  评论(0)    收藏  举报