我用for
循环制作了一些元素,我想获得值和来源,但似乎我不能。
我演示了我所做的here。
我的函数似乎只适用于for
循环创建的最后一个元素。
$("#emprev").click(function(){
var hisval = $(this).attr("value");
var hissrc = $(this).attr("src");
alert(hisval);
alert(hissrc);
});
答案 0 :(得分:4)
id
属性应该是唯一的,因此当您使用jquery按其ID获取元素时(使用#
),您将只获得第一个元素。
您应该使用这些类:
$(".emprev").click(function(){
var hisval = $(this).attr("value");
var hissrc = $(this).attr("src");
alert(hisval);
alert(hissrc);
});
以下是对您的代码的更新:
var emval = [':D',':C','8)',':O',':)','._.',':heart:',':P',';P',';)',':(','.-.','-.-'];
var emsrc = ['http://emojipedia-us.s3.amazonaws.com/cache/18/2f/182fa3786046d170707fa46a257185cb.png','http://emojipedia-us.s3.amazonaws.com/cache/c5/a5/c5a5a52fa1633e19ab2648f23ab1ee37.png','http://emojipedia-us.s3.amazonaws.com/cache/c1/2c/c12c7f3797ed8fcdcbedffb2649abfb1.png','http://emojipedia-us.s3.amazonaws.com/cache/55/af/55af488f029266842c13a54d4c50fc11.png','http://emojipedia-us.s3.amazonaws.com/cache/be/22/be22105632cfc32abf7b24bed3924e12.png','http://emojipedia-us.s3.amazonaws.com/cache/ce/1a/ce1a33d6a4535ce73c8b2b899d51071b.png','http://emojipedia-us.s3.amazonaws.com/cache/3e/f0/3ef0aeaf797844b672df6198c53ba479.png','http://emojipedia-us.s3.amazonaws.com/cache/43/be/43be98eee74f44eddec9c3137b1edf28.png','http://emojipedia-us.s3.amazonaws.com/cache/7e/d5/7ed517c9f335c3171b6f92685514667a.png','http://emojipedia-us.s3.amazonaws.com/cache/58/be/58be1ae13dbf3fb471f7f598a0365734.png','http://emojipedia-us.s3.amazonaws.com/cache/0c/04/0c04f9fd77dc486724c269587028e7d2.png','http://emojipedia-us.s3.amazonaws.com/cache/e6/7c/e67c860bd5cd2b9b443516171ec3c6a3.png','http://emojipedia-us.s3.amazonaws.com/cache/c1/05/c105ab901e2fa6e67b38879bcc0ac0b0.png'];
$(document).ready(function () {
for (var i = 0; i <= 12; i++) {
img = $('<img class="emprev" width="32px" height="32px" style="margin-bottom:3px;margin-left:4px;margin-top:2px">')
img.attr("value", emval[i]);
img.attr("src", emsrc[i]);
$("#emoji-list").prepend(img)
}
$(".emprev").click(function(){
var hisval = $(this).attr("value");
var hissrc = $(this).attr("src");
alert(hisval);
alert(hissrc);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="emoji-list" style="display:block;width:290px;height:200px;background:#ecebeb;border:1px solid black;border-radius:5px;position:absolute;bottom:150px;left:52%;z-index:9999999"></div>
请注意,我还对您的代码进行了一些小的更改,以确保其中的所有内容都能正常运行