创建动态按钮时出现错误,以及如何在不使用id的情况下动态添加单击事件

error while creating dynamic button and how to add click event dynamically without using id

本文关键字:动态 id 情况下 事件 单击 添加 按钮 错误 创建      更新时间:2023-09-26
var shoplink=  $("<button></button>")
               .prop("id",i)
               .val("view more")
               .css({
                     width: '20px'
                     height: '20px'
               });

当我使用这个按钮js文件不工作。我想添加点击事件的按钮动态不使用id。

CSS函数参数错误,您错过了,buttonvalue attr仅用于表单数据,因此您应该使用text()函数而不是val()

.css({
 width: '20px' ,
height: '20px' /'
});             |----------------  

Try this

 var shoplink=$("<button></button>")
    .prop("id","idBUTTON")
    .text("view more")
    .css({
     width: '20px',
    height: '20px'
    });
演示

try with逗号

var shoplink = $('<button></button>')
               .prop('id',i)
               .val('view more')
               .css( { width : '20px',height : '20px' });

当你定义多个css属性时需要加逗号

var shoplink=$("<button></button>")
.prop("id","asdasdasd")
.text("view more")
.val("view more")
.css({ "width": "20px", "height": "20px" });
演示

试试这个代码

  var shoplink=$("<button></button>")
    .prop("id",i)
    .val("view more")
    .css({
  width: '20px',
  height: '20px'
 });
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

<script type="text/javascript" >
$( document ).ready(function () {
var shoplink=$("<button>")
.prop("id","sad")
.val("view more")
.html("Test")
.css({
 width: '100px',
height: '20px'
});
$("#test").append(shoplink);
 });
</script>
</head>
<body>
<div id="test" ></div>
</body>
</html>