简体   繁体   中英

Passing variable to javascript function with symbols like colon, semicolon, etc

Currently I am stock on this scenario on my current function.

Basically, this ajax call will generate list of emoticons, however I want that when a user clicks on a smiley image, the smiley code will be added to message textbox.

Like for example, when user clicks on smiling image, the :-) code will be added to the message box. My question is, Is it possible to pass the code :-) to a function?

On my current codes, addText(' + key + ') is not working. The value of key is :-) . Error says Uncaught SyntaxError: Unexpected token : And when the value is ;) the error is Uncaught SyntaxError: Unexpected token ; I also have :lol: etc. codes similar to that. Any help will be much appreciated.

$.ajax({
    type: "POST",
    async: true,
    cache: false,
    dataType: "json",
    url: "./assets/php/scripts.php",
    data: {command: 'get-smileys'},
    success: function (data) {
        $("#smileys").empty();
        $("#smileys").append("<br>");
        var div_obj = document.createElement("ul");
        $(div_obj).addClass('list-inline');
        $.each(data, function(key, value) {
            $(div_obj).append('<li><div class="col-xs-1 col-sm-1 col-lg-1" style="width:110px; height:80px" align="center"><img src="assets/img/smileys/' + value[0] + '" title="' + value[1] + '" onclick="addText(' + key + ');"><br>' + key + '</div></li>')
            $("#smileys").append($(div_obj)); 
        });
        $("#smileys-flag").text('1');
        $("#loader-chat").hide();
    }
});

And here's the function in adding text part:

function addText(text){
    var fullMessage = $("#message").val();
    $("#message").val(fullMessage + text);
}

The problem is you need to pass them as string literals as given below.

'" onclick="addText(\'' + key + '\');"><br>'

But a better solution will be to use a jQuery event handler instead of a inline one like

$(div_obj).append('<li><div class="col-xs-1 col-sm-1 col-lg-1" style="width:110px; height:80px" align="center"><img class="smileys" src="assets/img/smileys/' + value[0] + '" title="' + value[1] + '" data-smiley="' + key + '"><br>' + key + '</div></li>')

then

jQuery(function ($) {
    $("#smileys").on('click', '.smileys', function () {
        addText($(this).data('smiley'))
    });
})

You need to pass your args as string literals. Then when you are decoding it you can just get the substring you want.

For example:

function takeSmiley(smiley) {
  return smiley.substr(1, smiley.length - 2) // Return lol for :lol:
}

takeSmiley(":lol:");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM