不能改变span的内容

Can't change span content

本文关键字:span 能改变 不能      更新时间:2023-09-26

我已经有了这个span:

<span id="inicial"></span>

和这个javascript在一个按钮里面点击:

    var pat = /'/'S+'//i;
    context = '';
    context = $('#cmd').attr('value');
    context= context.match(pat);
alert(context); //this gives correctly the string i need    
if (context.length){
    $('#inicial').text(context); //but it fails to change the text inside the span
    }

有什么问题吗?

我也注意到,它影响整个点击功能,它只是停止工作。可能的原因是什么?

问题是.match()返回数组,而不是字符串。但.text(parm)要求parm字符串

所以在.match()之后,你应该这样做:

context = context[0];

或使用其他方法至少将数组中的第一个元素转换为字符串,如果不是整个数组的话。

以下是.match()的参考:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match

.text(parm)的ref: http://api.jquery.com/text/

try -按@Jonathan M编辑回答

$('#inicial').html(context[0]);