Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 调用字符串时出错:indexOf_Javascript_Indexof - Fatal编程技术网

Javascript 调用字符串时出错:indexOf

Javascript 调用字符串时出错:indexOf,javascript,indexof,Javascript,Indexof,行var ndx=url.indexOf(参数)导致代码返回而不显示以下任何警报。显示url的警报是正确的 function setFrameSrc() { var url = document.location; if (null == url) { alert('Javascript Error: Null Object - document.location'); return; } alert('URL = ' + url)

var ndx=url.indexOf(参数)导致代码返回而不显示以下任何警报。显示url的警报是正确的

function setFrameSrc() {
    var url = document.location;
    if (null == url) {
        alert('Javascript Error: Null Object - document.location');
        return;
    }
    alert('URL = ' + url);

    var parameter = '?image=';
    var ndx = url.indexOf(parameter);
    if (ndx < 0) {
        alert('Parameter not found = ' + parameter);
        return;
    }
    alert('Index of ' + parameter + ' = ' + ndx);

    var frame = document.getElementById('pframe');
    if (null == frame) {
        alert('Javascript Error: Null Object - frame');
        return;
    }
    frame.src = url.substring(ndx);
}
函数setFrameSrc(){
var url=document.location;
if(null==url){
警报('Javascript错误:Null对象-document.location');
返回;
}
警报('URL='+URL);
变量参数='?图像=';
var ndx=url.indexOf(参数);
如果(ndx<0){
警报(“未找到参数=”+参数);
返回;
}
警报('+参数+'='+ndx的索引);
var frame=document.getElementById('pframe');
if(null==帧){
警报('Javascript错误:空对象-帧');
返回;
}
frame.src=url.substring(ndx);
}

此代码有什么问题?

文档。位置
,尽管其外观不是字符串。您需要
document.location.href

更好的是,您可以使用
document.location.search
,它只包括包含
(不包括
#
,之后您不考虑的部分)。

更改:
var url=document.location

致(以下其中一项):
  • var url=document.location+''
    注意:您还需要将
    null
    比较更改为空字符串(
    '

  • (url+“”).indexOf

  • 这对我有用:

    function test(){
    var url = location.href;
    if ( null == url ) {
        alert( 'Javascript Error: Null Object - document.location' );
    return;
    }
    alert( 'URL = ' + url );
    
    
    var parameter = '?image=';
    var ndx = url.toLowerCase().indexOf( parameter );
    alert(ndx);
    if ( ndx < 0 ) {
        alert( 'Parameter not found = ' + parameter );
        return;
    }
    alert( 'Index of ' + parameter + ' = ' + ndx );
    }
    
    test();
    
    功能测试(){
    var url=location.href;
    if(null==url){
    警报('Javascript错误:Null对象-document.location');
    返回;
    }
    警报('URL='+URL);
    变量参数='?图像=';
    var ndx=url.toLowerCase().indexOf(参数);
    警报(ndx);
    如果(ndx<0){
    警报('未找到参数='+参数);
    返回;
    }
    警报('索引'+参数+'='+ndx);
    }
    test();
    
    更改:document.locationlocation.href