Javascript-форум (https://javascript.ru/forum/)
-   Javascript под браузер (https://javascript.ru/forum/css-html/)
-   -   Падение при вызове функции (https://javascript.ru/forum/css-html/80090-padenie-pri-vyzove-funkcii.html)

Игорь №111111111111111111 25.04.2020 22:11

Падение при вызове функции
 
Почему если вызвать
$( function() {
$( '.11' ).dropdown( {
gutter : 5,
slidingIn : 100
} );
});

тогда выходит TypeError: KWeb is null и все не работает:( :help:

<div id="content">
<div id="searchContainer">
<div id="searchForm">
<div id="searchLogoContainer">
<img id="searchEngineLogo"/>
</div>
<img id="sIMG" src="" />
<input type="search" name="q" id="searchText" maxlength="256"  autofocus="autofocus" placeholder="2" results="0" onkeypress='if(event.keyCode==13){KSearch(true);} '/>
<input id="searchSubmit" type="button" value="3" onclick="KSearch(true);"/>
</div>
<br/>
<select  id="KSType"></select>
</div>
</div>  
<section class="main clearfix">
<select class="11" name="KSWeb" id="KSWeb" onchange="KSearch(false);">
  <option class="text" value="Yandex">Яндекс</option>
  <option class="text" value="Google">Google</option>
  <option class="text" value="Wikipedia">Wikipedia</option>
  <option class="text" value="youtube">Youtube</option>
  <option class="text" value="Bing">Bing</option>
  <option class="text" value="duckduckgo">DuckDuckGo</option>
</select>
</section>


function KSearch(sGo)
{
var KWeb,KWebindex,Ktype,Ktypeindex,gsearchForm,tStyle,sURL;
KWeb=document.getElementById('KSWeb');
KWebindex=KWeb.selectedIndex;
 
Ktype=document.getElementById('KSType');
Ktypeindex=Ktype.selectedIndex;
 
gsearchForm=document.getElementById('searchForm');
gsearchFac=gsearchForm.action;
 
gsearchtext=document.getElementById('searchText');
 
tStyle=Ktype.style;
 
sImage=document.getElementById('sIMG');
 
 
 
 
 
switch (KWeb.value)
{
    case "Google":
 
    if(Ktypeindex){
      sURL="http://www.google.com/images?q=";
      }else{
      sURL="http://www.google.com/search?num=100&amp;q=";      
      }
    tStyle.display='none';
    sImage.src="google2.png"
        break;
    
    case "Yandex":
    if(Ktypeindex){
      sURL="https://yandex.ru/images/search?clid=2295666&amp;text=";
      }else{
      sURL="https://yandex.ru/search/?clid=2295666&amp;text=";      
      }
    tStyle.display='none';
        sImage.src="Yandex.png"
 
        break;
 
        
    case "Bing":
        if(Ktypeindex){
      sURL="http://www.bing.com/images/search?q=";
      }else{
      sURL="http://www.bing.com/search?q=";      
      }
    tStyle.display='none';
        sImage.src="bing.png"
 
        break;
 
        
    case "Wikipedia":
      sURL="http://ru.wikipedia.org/w/index.php?title=Special%3ASearch&amp;fulltext=Search&amp;search=";      
 
        tStyle.display='none';
        sImage.src="Wikipedia.png"
 
        break;
        
    case "youtube":
      sURL="http://www.youtube.com/results?search_query=";      
 
        tStyle.display='none';
        sImage.src="youtube.png"
 
        break;
 
        
    case "duckduckgo":
      sURL="http://duckduckgo.com/?q=";
         
        tStyle.display='none';
    sImage.src="DC.png"
        break;
        
    default:
      sURL="https://www.google.com/search?btnI=1&amp;q=";   
        tStyle.display='none';
    sImage.src="google.png"
 
}
 
 
 
if (sGo)
{
sURL=sURL+gsearchtext.value;
 
//alert(sURL)
 
window.location=sURL;
 
 
 
}
 
 
}
            $( function() {
                
                $( '.11' ).dropdown( {
                    gutter : 5,
                    stack : false,
                    slidingIn : 100
                } );
 
            });

рони 25.04.2020 22:15

Игорь №111111111111111111,
:-?

Игорь №111111111111111111 26.04.2020 10:06

Что?
Я в js дурачек....:cray:

Игорь №111111111111111111 26.04.2020 10:13

Консоль говорит что ошибка в стоке 5
KWebindex=KWeb.selectedIndex;

рони 26.04.2020 10:24

Игорь №111111111111111111,
вероятно ваш плагин удаляет select , заменяет его, а раз нет select значит нет индекса. читать документацию на плагин и переносить onchange="KSearch(false);" в плагин.

Игорь №111111111111111111 26.04.2020 17:23

Спасай :yes:
https://drive.google.com/open?id=1nw...0Qm6Q7jdf8mOdp

Пожалуйста :)

рони 26.04.2020 18:17

Игорь №111111111111111111,
не могу помочь, могу только гадать, что находится по указанной вами ссылке, может вы измените логику и откажитесь искать selectedIndex(в большинстве случаев это не нужно, в select важно значение value), тем более это у вас нигде не используется, просто удалите строку 5.

Игорь №111111111111111111 26.04.2020 18:53

Если удалить строку 5 тогда ошибка возникает в строке 20
и на это все.....
(ссылка на архив с исходником в гугл диске)

рони 26.04.2020 18:56

Цитата:

Сообщение от Игорь №111111111111111111
(ссылка на архив с исходником в гугл диске)

не могу помочь

Игорь №111111111111111111 26.04.2020 19:10

А если так? :help:
function KSearch(sGo)
{
var KWeb,KWebindex,Ktypeindex,gsearchForm,sURL;
KWeb=document.getElementById('KSWeb');
KWebindex=KWeb.selectedIndex;






gsearchtext=document.getElementById('searchText');


sImage=document.getElementById('sIMG');





switch (KWeb.value)
{
    case "Google":

    if(Ktypeindex){
      sURL="http://www.google.com/images?q=";
      }else{
      sURL="http://www.google.com/search?num=100&amp;q=";      
      }
    
    sImage.src="css/fonts/google.png"
        break;
    
    case "Yandex":
    if(Ktypeindex){
      sURL="https://yandex.ru/images/search?clid=2295666&amp;text=";
      }else{
      sURL="https://yandex.ru/search/?clid=2295666&amp;text=";      
      }
    
        sImage.src="css/fonts/Yandex.png"

        break;

        
    case "Bing":
        if(Ktypeindex){
      sURL="http://www.bing.com/images/search?q=";
      }else{
      sURL="http://www.bing.com/search?q=";      
      }
    
        sImage.src="css/fonts/bing.png"

        break;

        
    case "Wikipedia":
      sURL="http://ru.wikipedia.org/w/index.php?title=Special%3ASearch&amp;fulltext=Search&amp;search=";      

        
        sImage.src="css/fonts/Wikipedia.png"

        break;
        
    case "youtube":
      sURL="http://www.youtube.com/results?search_query=";      

        
        sImage.src="css/fonts/youtube.png"

        break;

        
    case "duckduckgo":
      sURL="http://duckduckgo.com/?q=";
         
        
	sImage.src="css/fonts/DC.png"
        break;
        
    default:
      sURL="https://www.google.com/search?btnI=1&amp;q=";   
        
	sImage.src="css/fonts/google.png"

}



if (sGo)
{
sURL=sURL+gsearchtext.value;

//alert(sURL)

window.location=sURL;



}


}
			$( function() {
				
				$( '#KSWeb' ).dropdown( {
					gutter : 5,
					stack : false,
					slidingIn : 100
				} );

			});

Игорь №111111111111111111 26.04.2020 19:11

/**
 * jquery.dropdown.js v1.0.0
 * [url]http://www.codrops.com[/url]
 *
 * Licensed under the MIT license.
 * [url]http://www.opensource.org/licenses/mit-license.php[/url]
 *
 * Copyright 2012, Codrops
 * [url]http://www.codrops.com[/url]
 */
;( function( $, window, undefined ) {

	'use strict';

	$.DropDown = function( options, element ) {
		this.$el = $( element );
		this._init( options );
	};

	// the options
	$.DropDown.defaults = {
		speed : 300,
		easing : 'ease',
		gutter : 0,
		// initial stack effect
		stack : true,
		// delay between each option animation
		delay : 0,
		// random angle and positions for the options
		random : false,
		// rotated [right||left||false] : the options will be rotated to thr right side or left side.
		// make sure to tune the transform origin in the stylesheet
		rotated : false,
		// effect to slide in the options. value is the margin to start with
		slidingIn : false,
		onOptionSelect : function(opt) { return false; }
	};

	$.DropDown.prototype = {

		_init : function( options ) {

			// options
			this.options = $.extend( true, {}, $.DropDown.defaults, options );
			this._layout();
			this._initEvents();

		},
		_layout : function() {

			var self = this;
			this.minZIndex = 1000;
			this._transformSelect();
			this.opts = this.listopts.children( 'li' );
			this.optsCount = this.opts.length;
			this.size = { width : this.dd.width(), height : this.dd.height() };
			
			var elName = this.$el.attr( 'name' ), elId = this.$el.attr( 'id' ),
				inputName = elName !== undefined ? elName : elId !== undefined ? elId : 'KSWeb-' + ( new Date() ).getTime();

			this.inputEl = $( '<input type="hidden" name="' + inputName + '"></input>' ).insertAfter( this.selectlabel );
			
			this.selectlabel.css( 'z-index', this.minZIndex + this.optsCount );
			this._positionOpts();
			if( Modernizr.csstransitions ) {
				setTimeout( function() { self.opts.css( 'transition', 'all ' + self.options.speed + 'ms ' + self.options.easing ); }, 25 );
			}

		},
		_transformSelect : function() {

			var optshtml = '', selectlabel = '';
			this.$el.children( 'option' ).each( function() {

				var $this = $( this ),
					val = isNaN( $this.attr( 'value' ) ) ? $this.attr( 'value' ) : Number( $this.attr( 'value' ) ) ,
					classes = $this.attr( 'class' ),
					label = $this.text();

				val !== -1 ?
					classes !== undefined ?
						optshtml += '<li data-value="' + val + '"><span class="' + classes + '">' + label + '</span></li>' :
						optshtml += '<li data-value="' + val + '"><span>' + label + '</span></li>' :
					selectlabel = label;

			} );

			this.listopts = $( '<ul/>' ).append( optshtml );
			this.selectlabel = $( '<span/>' ).append( selectlabel );
			this.dd = $( '<div class="KSWeb"/>' ).append( this.selectlabel, this.listopts ).insertAfter( this.$el );
			this.$el.remove();

		},
		_positionOpts : function( anim ) {

			var self = this;

			this.listopts.css( 'height', 'auto' );
			this.opts
				.each( function( i ) {
					$( this ).css( {
						zIndex : self.minZIndex + self.optsCount - 1 - i,
						top : self.options.slidingIn ? ( i + 1 ) * ( self.size.height + self.options.gutter ) : 0,
						left : 0,
						marginLeft : self.options.slidingIn ? i % 2 === 0 ? self.options.slidingIn : - self.options.slidingIn : 0,
						opacity : self.options.slidingIn ? 0 : 1,
						transform : 'none'
					} );
				} );

			if( !this.options.slidingIn ) {
				this.opts
					.eq( this.optsCount - 1 )
					.css( { top : this.options.stack ? 9 : 0, left : this.options.stack ? 4 : 0, width : this.options.stack ? this.size.width - 8 : this.size.width, transform : 'none' } )
					.end()
					.eq( this.optsCount - 2 )
					.css( { top : this.options.stack ? 6 : 0, left : this.options.stack ? 2 : 0, width : this.options.stack ? this.size.width - 4 : this.size.width, transform : 'none' } )
					.end()
					.eq( this.optsCount - 3 )
					.css( { top : this.options.stack ? 3 : 0, left : 0, transform : 'none' } );
			}

		},
		_initEvents : function() {
			
			var self = this,
				throwHook = this._throwHook;
			
			this.selectlabel.on( 'mousedown.dropdown', function( event ) {
				self.opened ? self.close() : self.open();
				return false;

			} );

			this.opts.on( 'click.dropdown', function() {
				if( self.opened ) {
					var opt = $( this );
					self.options.onOptionSelect( opt );
					self.inputEl.val( opt.data( 'value' ) );
					self.selectlabel.html( opt.html() );
					self.close();
				}
			} );

		},
		open : function() {
			var self = this;
			this.dd.toggleClass( 'cd-active' );
			this.listopts.css( 'height', ( this.optsCount + 1 ) * ( this.size.height + this.options.gutter ) );
			this.opts.each( function( i ) {

				$( this ).css( {
					opacity : 1,
					top : self.options.rotated ? self.size.height + self.options.gutter : ( i + 1 ) * ( self.size.height + self.options.gutter ),
					left : self.options.random ? Math.floor( Math.random() * 11 - 5 ) : 0,
					width : self.size.width,
					marginLeft : 0,
					transform : self.options.random ?
						'rotate(' + Math.floor( Math.random() * 11 - 5 ) + 'deg)' :
						self.options.rotated ?
							self.options.rotated === 'right' ?
								'rotate(-' + ( i * 5 ) + 'deg)' :
								'rotate(' + ( i * 5 ) + 'deg)'
							: 'none',
					transitionDelay : self.options.delay && Modernizr.csstransitions ? self.options.slidingIn ? ( i * self.options.delay ) + 'ms' : ( ( self.optsCount - 1 - i ) * self.options.delay ) + 'ms' : 0
				} );

			} );
			this.opened = true;

		},
		close : function() {

			var self = this;
			this.dd.toggleClass( 'cd-active' );
			if( this.options.delay && Modernizr.csstransitions ) {
				this.opts.each( function( i ) {
					$( this ).css( { 'transition-delay' : self.options.slidingIn ? ( ( self.optsCount - 1 - i ) * self.options.delay ) + 'ms' : ( i * self.options.delay ) + 'ms' } );
				} );
			}
			this._positionOpts( true );
			this.opened = false;

		}

	}

	$.fn.dropdown = function( options ) {
		var instance = $.data( this, 'dropdown' );
		if ( typeof options === 'string' ) {
			var args = Array.prototype.slice.call( arguments, 1 );
			this.each(function() {
				instance[ options ].apply( instance, args );
			});
		}
		else {
			this.each(function() {
				instance ? instance._init() : instance = $.data( this, 'dropdown', new $.DropDown( options, this ) );
			});
		}
		return instance;
	};

} )( jQuery, window );

laimas 26.04.2020 19:20

Игорь №111111111111111111, индекс как и условия if(Ktypeindex) в данном случае лишены всякого смысла. Это вообще бессмыслица, ибо как может быть выполнится условие

else sURL="http://www.google.com/search?num=100&amp;q=";

при выборе в списке Гугла если индекс выбранной опции в этом случае ни как не может быть равен 0?

В вашем списке нельзя выбрать Яндекс без выбора иного в списке, то есть он может быть только значением по умолчанию. А чтобы можно было выбрать его в списке нужна опция предлагающая сделать выбор. В этом случае еще можно оперировать индексом опций, но это тоже ни к чему, проще оперировать значением списка (что и выполняется у вас), а первой опции предлагающей выбор установить пустое значение.

Причиной ошибки может быть выполнение функции в момент когда DOM еще не готов. Вряд ли какой-то плагин удаляет список, это и ни к чему да и не рационально.

рони 26.04.2020 19:28

Цитата:

Сообщение от laimas
Вряд ли какой-то плагин удаляет список,

пост 11 строка 91

laimas 26.04.2020 19:34

Цитата:

Сообщение от рони
пост 11 строка 91

Писал когда не было этого.


Часовой пояс GMT +3, время: 14:44.