javascript - 使用函数创建变量

标签 javascript jquery variables

我正在寻找一种使用函数创建变量的方法,因为我定义了用于在函数内部独立创建变量的变量,具体取决于用户的操作。

这是我拥有的,但它不起作用:

var popupContent = ''
var message = ''
var postLink = ''
function createMessage() {
    popupContent = [
        "<p>" + message + "</p>",
        "<form action='" + postLink + "' method='post' accept-charset='utf-8'>",
            "<ul class='cd-buttons no_margin'>",
                "<li><a class='submit'>Yes</a></li>",
                "<li><a class='popup-close'>No</a></li>",
            "</ul>",
        "</form>",
        "<a class='cd-popup-close popup-close img-replace'>Close</a>"
    ].join('');
}

//Accept Employement Request
$('.popup1').on('click', function() {
    employeeName = $(this).siblings('.js-employee-name').text();
    var message = "Are you sure you want to hire <b>" + employeeName + "</b>?"
    var postLink = "/hire-employee"

    createMessage();

    $(".cd-popup-container").append(popupContent);
});

JSFIDDLE

最佳答案

您可以按如下方式从函数返回内容,然后在 .append() 中调用该函数方法:

function createMessage(message, postLink) {
    return [
        "<p>" + message + "</p>",
        "<form action='" + postLink + "' method='post' accept-charset='utf-8'>",
            "<ul class='cd-buttons no_margin'>",
                "<li><a class='submit'>Yes</a></li>",
                "<li><a class='popup-close'>No</a></li>",
            "</ul>",
        "</form>",
        "<a class='cd-popup-close popup-close img-replace'>Close</a>"
    ].join('');
}

//Accept Employement Request
$('.popup1').on('click', function() {
    employeeName = $(this).siblings('.js-employee-name').text();
    var message = "Are you sure you want to hire <b>" + employeeName + "</b>?"
    var postLink = "/hire-employee"
    $(".cd-popup-container").append( createMessage(message, postLink) );
});

注意 您要传递所需的数据 messagepostLink作为函数的参数。 您不需要将这些变量声明或初始化为全局变量。您不想弄乱全局范围。它们是回调本地的,它们持有的数据将传递给 createMessage() .请注意变量 messagepostLink createMessage() 的参数是本地的 createMessage() .

DEMO

根据您的演示,我想知道使用 .html() 是否更合适?而不是 .append() !

关于javascript - 使用函数创建变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32188825/

相关文章:

javascript - 为公共(public) API GET 请求构建 JQuery getJSON 的查询字符串

c# - 使用 Javascript 更改 ActiveX 视频播放器源

javascript - 如何获取特定类的非兄弟元素的上一个和下一个元素

javascript - jquery 中动态生成的文本字段的不同名称

javascript - 从 Javascript 中的字符串中提取多个整数

javascript - jQuery Datepicker 输出格式化日期减去 1 个月

javascript - 如何通过我的模块化 js 结构中的 ajax 调用接收回数据?

javascript - 未定义值、变量范围问题

javascript - 使用 jQuery 编写应用程序 - 如何存储变量?

javascript - 在 js 变量中包含 &lt;script type ="text/javascript">.....&lt;/script&gt;