[英]Change class with data-target
I have tried this:我试过这个:
$(".font").click(function() { var target = $($(this).data("target")); $("#text").addClass(target); })
.pap { font-family: Papyrus; }.ar { font-family: Arial; }.hel { font-family: Helvetica, }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="font" data-target=".pap">Papyrus</button> <button class="font" data-target=".ar">Arial</button> <button class="font" data-target=".hel">Helvetica</button> <div id="text" class="ar">Text</div>
Unfortunately, it doesn't work to change the classes by clicking a button.不幸的是,通过单击按钮来更改类不起作用。 Is it just a little mistake or does this logic not work at all?这只是一个小错误还是这个逻辑根本不起作用?
Three problems:三个问题:
$(this).data("target")
,包装$(this).data("target")
,.
包括 class 选择器.
in target
dataset: data-target=".pap"
,在target
数据集中: data-target=".pap"
, $(".font").click(function() { var target = $(this).data("target"); // no double $ wrap // replace class because the first class listed takes precedence $("#text").attr('class', target); })
.pap { font-family: Papyrus; }.ar { font-family: Arial; }.hel { font-family: Helvetica, }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- notice no "dot" classname --> <button class="font" data-target="pap">Papyrus</button> <button class="font" data-target="ar">Arial</button> <button class="font" data-target="hel">Helvetica</button> <div id="text" class="ar">Text</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.