2014-07-26 2 views
0

긴 이야기 짧은 WordPress에서 만든 텍스트 영역을 편집해야합니다. ID와 기본값을 설정할 수 있지만 설정할 수는 없습니다. 이벤트 또는 다른 무엇이든지, 나는 사용자가 전화 번호를 입력하기 위해 클릭 한 후에 사라질 기본값을 원한다.jquery/javascript 함수는 방화 광 콘솔에서 작동하지만 페이지로드에서는 작동하지 않습니다.

내가 운이없이이 일을 여러 가지 방법을 시도, 일부는 다음과 같습니다

<script type="text/javascript"> 

    $(document).ready(function(){  
    // Your code goes here  

function clearOnInitialFocus ("telid01") { 
var clearedOnce = false; 
document.getElementById("telid01").onfocus = (function() { 
if (clearedOnce == false) { 
this.value = ''; 
clearedOnce = true; 
} 
}) 
} 
window.onload = function() { clearOnInitialFocus('telid01');} 

}); 
    </script> 

는 또한

<script type="text/javascript"> 
$(document).ready(function(){ 
document.getElementById('telid01').addEventListener('focus', function() { 
    this.value = ""; 
}); 
}); 
    </script> 

이 콘솔에서 작동을 시도하지만 페이지로드 :

document.getElementById('telid01').addEventListener('focus', function() { 
    this.value = ""; 

답변

0

이상한 방법으로 함수 매개 변수를 사용하고 있습니다. 나는 당신을 기반으로 다음과 같은 코드를 시도하고 잘 작동합니다.

<!doctype html> 
<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

<script type="text/javascript"> 

    $(document).ready(function(){  
    // Your code goes here  
     var clearedOnce = false; 
     document.getElementById("myTest").onfocus = 
     function() { 
      if (clearedOnce == false) { 
       this.value = ''; 
       clearedOnce = true; 
      } 
     }; 
    }); 
    </script> 

</head> 
<body> 
    <input id="myTest" value="placeholder" /> 
</body> 
</html> 
+3

그것은 작동하지 않습니다 ... 남자는 이미 나 자신을 죽일 수 있습니까? – octohedron

+0

이 예제가 별도의 .html 파일에서 작동하지 않습니까? 다른 브라우저를 사용해 볼 수 있습니까? –

+1

예 작품! 고마워! 아마도 ' – octohedron

1

jQuery를 사용하고 있으므로 다음과 같이 jQuery의 이벤트 바인딩을 사용할 수도 있습니다.

$(document).ready(function(){  
    var clearedOnce = false; 
    $(this).on('focus', '#telid01', function() { 
     if (!clearedOnce) { 
      $(this).val(''); 
      clearedOnce = true; 
     } 
    }); 
}); 

편집 : 이벤트를 '문서'에 첨부 한 다음 id를 선택기로 on()으로 전달하면 제대로 작동하고 페이지에 필드가 없는데도 이벤트를 첨부 할 수 있습니다. 참조 : http://api.jquery.com/on/

+1

나는 그것 때문에 wordpress 플러그인에 의해 완료되었으므로 textarea를 초기화 할 수 없습니다. 오직 ID, 클래스 및 기본값 만 설정할 수 있습니다. – octohedron

+0

여전히 작동하지 않습니다 : \ – octohedron

+0

이 코드를 시도하고 잘 작동합니다. 그래서 당신의 문제는 아마 다른 것에 의해 야기 될 것입니다. 'Alert()'를 JS 코드의 다른 장소에 삽입하여 실제로 실행중인 것을 확인하십시오. –

관련 문제