简体   繁体   English

如何将字符串与变量连接起来?

[英]How do I concatenate a string with a variable?

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?我怎么做?

I have something like this:我有这样的事情:

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

So how do I get that 'horseThumb' and an id into one string?那么如何将 'horseThumb' 和一个 id 放入一个字符串中呢?

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.我尝试了所有各种选项,我还用getElementById("horseThumb_{$id}")搜索,除了了解到我可以在字符串中插入一个变量,比如getElementById("horseThumb_{$id}") <-- (对我不起作用,我不知道为什么) 我发现没什么用。 So any help would be very appreciated.所以任何帮助将不胜感激。

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.也许您的问题是您没有将 ID 传递给AddBorder函数,或者具有该 ID 的元素不存在。 Or you might be running your function before the element in question is accessible through the browser's DOM.或者,您可能正在通过浏览器的 DOM 访问相关元素之前运行您的函数。

Since ECMAScript 2015, you can also use template literals (aka template strings) :从 ECMAScript 2015 开始,您还可以使用模板文字(又名模板字符串)

document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";

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));

That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById .每次调用该函数时都会打开弹出窗口,其中包含id的值和document.getElementById的返回值。 If you get undefined for the ID number pop-up, you are not passing an argument to the function.如果您undefined ID 号弹出窗口,则您没有将参数传递给函数。 If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.如果 ID 不存在,您会在第一个弹出窗口中得到您的(不正确?)ID 号,但在第二个弹出窗口中得到null

The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:如果您的网页看起来像这样,则会发生第三种情况,尝试在页面仍在加载时运行AddBorder

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

To fix this, put all the code that uses AddBorder inside an onload event handler:要解决此问题,请将所有使用 AddBorder 的代码放在onload事件处理程序中:

// 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);

In javascript the "+" operator is used to add numbers or to concatenate strings.在 javascript 中,“+”运算符用于添加数字或连接字符串。 if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.如果操作数之一是字符串“+”,则连接,如果它只是数字,则将它们相加。

example:例子:

1+2+3 == 6
"1"+2+3 == "123"

This can happen because java script allows white spaces sometimes if a string is concatenated with a number.这可能发生,因为如果字符串与数字连接,java 脚本有时允许空格。 try removing the spaces and create a string and then pass it into getElementById.尝试删除空格并创建一个字符串,然后将其传递给 getElementById。

example:例子:

var str = 'horseThumb_'+id;

str = str.replace(/^\s+|\s+$/g,"");

function AddBorder(id){

    document.getElementById(str).className='hand positionLeft'

}

It's just like you did.就像你做的一样。 And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax.对于这些愚蠢的事情,我会给你一个小技巧:只需使用浏览器 url 框来尝试 js 语法。 for example, write this: javascript:alert("test"+5) and you have your answer.例如,这样写: javascript:alert("test"+5)你就有了答案。 The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something.您的代码中的问题可能是该元素在您的文档中不存在......也许它在表单或其他东西中。 You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.您也可以通过在 url 中写入来测试: javascript:alert(document.horseThumb_5)以检查您的错误在哪里。

Another way to do it simpler using jquery.使用 jquery 更简单的另一种方法。

sample:样本:

function add(product_id){

    // the code to add the product
    //updating the div, here I just change the text inside the div. 
    //You can do anything with jquery, like change style, border etc.
    $("#added_"+product_id).html('the product was added to list');

}

Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.其中product_id 是javascript var 并且$("# added_"+product_id) 是一个div id 与product_id 连接,来自函数add 的var。

Best Regards!此致!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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