如何将字符串与变量连接? [英] How do I concatenate a string with a variable?

查看:88
本文介绍了如何将字符串与变量连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图用字符串和传递的变量(这是一个数字)来创建一个字符串。
我该怎么做?

So I am trying to make a string out of a string and a passed variable(which is a number). How do I do that?

我有这样的事情:

function AddBorder(id){
    document.getElementById('horseThumb_'+id).className='hand positionLeft'
}

那么如何将'horseThumb'和一个id变成一个字符串?

So how do I get that 'horseThumb' and an id into one string?

我尝试了所有各种选项,我也google了,除了学习我可以在字符串中插入一个变量,如 getElementById(horseThumb _ {$ id})< - (didn'为我工作,我不知道为什么)我没有发现任何有用的东西。所以任何帮助都将非常感激。

I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.

推荐答案

您的代码是正确的。也许您的问题是您没有将ID传递给 AddBorder 函数,或者具有该ID的元素不存在。或者您可能在通过浏览器的DOM访问相关元素之前运行您的函数。

Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.

要识别第一种情况或确定第二种情况的原因,请添加这些作为函数内的第一行:

To identify the first case or determine the cause of the second case, add these as the first lines inside the function:

alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));

这将在每次调用函数时打开弹出窗口,其值为 id 以及的返回值document.getElementById 。如果您为ID号弹出窗口获得 undefined ,则不会将参数传递给该函数。如果该ID不存在,您将在第一个弹出窗口中获得(错误的?)ID号,但在第二个弹出窗口中获得 null

That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.

如果您的网页看起来像这样,在页面仍在加载时尝试运行 AddBorder ,则会发生第三种情况:

The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:

<head>
<title>My Web Page</title>
<script>
    function AddBorder(id) {
        ...
    }
    AddBorder(42);    // Won't work; the page hasn't completely loaded yet!
</script>
</head>

要解决此问题,请将使用AddBorder的所有代码放在 onload <中/ code>事件处理程序:

To fix this, put all the code that uses AddBorder inside an onload event handler:

// Can only have one of these per page
window.onload = function() {
    ...
    AddBorder(42);
    ...
} 

// Or can have any number of these on a page
function doWhatever() {
   ...
   AddBorder(42);
   ...
}

if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);

这篇关于如何将字符串与变量连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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