jQuery-将字符串视为变量名并返回其值 [英] jQuery - treating a string as a variable name and returning its value

查看:81
本文介绍了jQuery-将字符串视为变量名并返回其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多包含文本字符串的变量,想要选择要根据所单击元素显示的变量.

I have a number of variables containing text strings and want to select which should be shown based on the element that is clicked.

下面的代码是我正在尝试做的一个非常简化的版本,目前将.msgBox的innerHTML设置为'A_msg'或'B_msg',我想要将其设置为这些变量的值.

The code below is a very simplified version of what I'm trying to do, at the moment it sets the innerHTML of .msgBox to 'A_msg' or 'B_msg', what I want it to do is set it to the value of those variables.

    var A_msg = "You clicked A";
    var B_msg = "You clicked B";

    $(".trigger").mouseover(function() {
      var MsgToDisplay = $(this).attr('id')+"_msg";
      $('#msgBox').html(MsgToDisplay);
    });

    <div class="trigger" id="A">Option A</div>
    <div class="trigger" id="B">Option B</div>
    <div id="msgBox"></div>

推荐答案

您应使用一个对象:

var messages = {
    A: "You clicked A",
    B: "You clicked B"
};

$(".trigger").mouseover(function() {
  var MsgToDisplay = messages[$(this).attr('id')];
  $('#msgBox').html(MsgToDisplay);
});

您可以编写messages[someString]以按名称获取属性的值.

You can write messages[someString] to get the value of property by name.

这篇关于jQuery-将字符串视为变量名并返回其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆