在 jQuery 选择器中连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12134605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:21:32  来源:igfitidea点击:

Concatenate in jQuery Selector

jqueryconcatenation

提问by jason328

Simple problem. I have a js variable I want to be concatenated too within a jQuery selector. However it is not working. No errors are popping up either. What is wrong? How do I correctly concatenate a variable to some text in a jQuery selector.

简单的问题。我有一个 js 变量,我也想在 jQuery 选择器中进行连接。但是它不起作用。也没有出现错误。怎么了?如何正确地将变量连接到 jQuery 选择器中的某些文本。

<div id="part2"></div>

<script type="text/javascript" >

$('#button').click(function () 
{
var text = $('#text').val();    
var number = 2;
$.post('ajaxskeleton.php', {
red: text       
}, 
    function(){
    $('#part' + number).html(text);
    }); 
});


</script> 

回答by sabithpocker

There is nothing wrong with syntax of

的语法没有任何问题

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Nodeas parameter to create a jQuery Object.

jQuery 接受一个字符串(通常是一个 CSS 选择器)或一个DOM 节点作为参数来创建一个jQuery 对象

In your case you should pass a String to $()that is

在您的情况下,您应该将一个字符串传递给$()

$(<a string>)

Make sure you have access to the variables numberand text.

确保您可以访问变量numbertext.

To test do:

测试做:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

如果您发现您无权访问,请将它们作为参数传递给函数,您必须包含 $.get 的 uual 参数并在它们之后传递自定义参数。

回答by Alnitak

Your concatenation syntax is correct.

您的连接语法是正确的。

Most likely the callback function isn't even being called. You can test that by putting an alert(), console.log()or debuggerline in that function.

很可能甚至没有调用回调函数。您可以通过在该函数中放置alert(),console.log()debuggerline来测试它。

If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail()handler after $.post()to find out what the error is, e.g.:

如果它没有被调用,很可能是 AJAX 错误。查看链接.fail()处理程序之后$.post()找出错误是什么,例如:

$.post('ajaxskeleton.php', {
    red: text       
}, function(){
    $('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(arguments);
});