Javascript 创建动态按钮时出错,以及如何在不使用id的情况下动态添加单击事件 var shoplink=$(“”) .prop(“id”,i) .val(“查看更多”) .css({ 宽度:“20px” 高度:“20px” });

Javascript 创建动态按钮时出错,以及如何在不使用id的情况下动态添加单击事件 var shoplink=$(“”) .prop(“id”,i) .val(“查看更多”) .css({ 宽度:“20px” 高度:“20px” });,javascript,Javascript,使用此按钮时,js文件不起作用。我想在不使用id的情况下为按钮动态添加单击事件。尝试使用逗号 var shoplink= $("<button></button>") .prop("id",i) .val("view more") .css({ width: '20px' height: '20px

使用此按钮时,js文件不起作用。我想在不使用id的情况下为按钮动态添加单击事件。

尝试使用逗号

var shoplink=  $("<button></button>")
               .prop("id",i)
               .val("view more")
               .css({
                     width: '20px'
                     height: '20px'
               });
var shoplink=$(“”)
.prop('id',i)
.val('查看更多')
.css({宽度:'20px',高度:'20px'});

CSS函数参数工作,您错过了
按钮
属性仅用于表单数据,因此您应该使用
text()
函数而不是
val()

试试这个

.css({
 width: '20px' ,
height: '20px' /\
});             |----------------  
var shoplink=$(“”)
.prop(“id”、“idBUTTON”)
.text(“查看更多”)
.css({
宽度:“20px”,
高度:“20px”
});

试试这段代码

 var shoplink=$("<button></button>")
    .prop("id","idBUTTON")
    .text("view more")
    .css({
     width: '20px',
    height: '20px'
    });
var shoplink=$(“”)
.prop(“id”,i)
.val(“查看更多”)
.css({
宽度:“20px”,
高度:“20px”
});

$(文档).ready(函数(){
var shoplink=$(“”)
.prop(“id”、“sad”)
.val(“查看更多”)
.html(“测试”)
.css({
宽度:“100px”,
高度:“20px”
});
$(“#测试”).append(shoplink);
});

定义多个css属性时,需要添加逗号

<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>
var shoplink=$(“”)
.道具(“id”、“asdasdasd”)
.text(“查看更多”)
.val(“查看更多”)
.css({“宽度”:“20px”,“高度”:“20px”});

我能看一下html代码吗?你到底把代码放在哪里了?请提供更多信息(脚本和标记)。此字段为新字段,因此只需询问“单击我”!检查此按钮是否有属性value@Unknownman谢谢评论,我已经更新了答案,但OP只想显示按钮文本。
  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>
var shoplink=$("<button></button>")
.prop("id","asdasdasd")
.text("view more")
.val("view more")
.css({ "width": "20px", "height": "20px" });