我正在使用qrcode.js生成qrcode。我想每次单击进入“添加新标签”而不是添加新的二维码时都生成随机QR码。我为随机数创建了一个代码,但是当我尝试添加onclick函数时,它会添加新内容而不是随机数。

JSFIDDLE:https://jsfiddle.net/aice09/L8pp9336/
GITHUB:https://github.com/Ailyn09/project102/blob/master/qrcode.html
CODEPEN:https://codepen.io/aice09/pen/Ogqajr

$('#lithird').click(function() {

    var qrcode = new QRCode("qrcode");

    function makeCode() {

        function randomNumber(len) {
            var randomNumber;
            var n = '';

            for (var count = 0; count < len; count++) {
                randomNumber = Math.floor(Math.random() * 10);
                n += randomNumber.toString();
            }
            return n;
        }

        var value = randomNumber(13);

        var elText = value;

        qrcode.makeCode(elText);
    }

    makeCode();

});    
#qrcode {
  width:160px;
  height:160px;
  margin-top:15px;
}
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid" id="main">
    <ul class="nav nav-tabs" role="tablist">
        <li role="presentation" id="lifirst" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">List</a></li>
        <li role="presentation" id="lithird"><a href="#editable" aria-controls="editable" role="tab" data-toggle="tab" onclick='transfer_new()'>Add New</a></li>
    </ul>
    <!--/ Nav tabs /-->

    <!-- Tab panes -->
    <div class="tab-content">
        <div role="tabpanel" class="tab-pane active" id="home" style="margin-top:  10px;">
            IN THE NEXT TABA THE AR CODE
        </div>
        <div role="tabpanel" class="tab-pane" id="editable">

            <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 col-md-offset-4 col-lg-offset-4">
                <div id="qrcode"></div>
            </div>=
        </div>
    </div>
</div>

最佳答案

尝试将$('#qrcode').html('');添加为.click(function(){}中的第一项

像这样:

$('#lithird').click(function(){

    $('#qrcode').html('');  // <---Add this, which should clear it out on the next click

    var qrcode = new QRCode("qrcode");

    function makeCode () {

        function randomNumber(len) {
        var randomNumber;
        var n = '';

        for(var count = 0; count < len; count++) {
            randomNumber = Math.floor(Math.random() * 10);
            n += randomNumber.toString();
        }
        return n;
    }

    var value = randomNumber(13);
        var elText = value;

        qrcode.makeCode(elText);
    }

    makeCode();

});

Codepen for full review

关于javascript - 使用qrcode.js生成随机QR Code OnClick,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45115027/

10-13 00:56