jquery를 통해 앵커 클릭을 어떻게 시뮬레이트 할 수 있습니까?
jQuery를 통해 앵커 클릭을 가짜로 만드는 데 문제가 있습니다. 입력 버튼을 처음 클릭 할 때 thickbox가 나타나는 이유는 무엇입니까?
내 코드는 다음과 같습니다.
<input onclick="$('#thickboxId').click();" type="button" value="Click me" />
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
링크를 직접 클릭하면 항상 작동하지만 입력 버튼을 통해 thickbox를 활성화하려고하면 작동하지 않습니다. 이것은 FF입니다. Chrome의 경우 매번 작동하는 것 같습니다. 힌트가 있습니까?
그런 jQuery 호출을 인라인하지 마십시오. 페이지 상단에 스크립트 태그를 넣어 click
이벤트 에 바인딩하십시오 .
<script type="text/javascript">
$(function(){
$('#thickboxButton').click(function(){
$('#thickboxId').click();
});
});
</script>
<input id="thickboxButton" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
편집하다:
링크를 실제로 클릭하는 사용자를 시뮬레이트하려는 경우 가능하지 않다고 생각합니다. 해결 방법은 버튼 click
이벤트를 업데이트하여 window.location
Javascript 를 변경하는 것 입니다.
<script type="text/javascript">
$(function(){
$('#thickboxButton').click(function(){
window.location = $('#thickboxId').attr('href');
});
});
</script>
편집 2 :
Thickbox가 사용자 정의 jQuery UI 위젯이라는 것을 알았으므로 여기 에서 지침을 찾았습니다 .
명령:
- 링크 요소 만들기 (
<a href>
) - 링크에 thickbox (
class="thickbox"
) 값을 가진 클래스 속성을 제공하십시오. - 에서
href
링크의 속성을 다음과 앵커를 추가 :#TB_inline
에서
href
애프터 속성#TB_inline
추가 앵커에에서 다음 쿼리 문자열 :? height = 300 & width = 300 & inlineId = myOnPageContent
쿼리에서 높이, 너비 및 inlineId 값을 적절히 변경하십시오 (inlineID는 ThickBox에 표시 할 내용이 포함 된 요소의 ID 값입니다).
- 선택적
#TB_inline?height=155&width=300&inlineId=hiddenModalContent&modal=true
으로 ThickBox를 닫을 때 ThickBoxtb_remove()
내에서 함수를 호출하도록 modal = true를 쿼리 문자열 (예 :)에 추가 할 수 있습니다 . ThickBox를 닫으려면 예 또는 아니오를 클릭해야하는 숨겨진 모달 컨텐츠 예제를 참조하십시오.
나를 위해 일한 것은 다음과 같습니다.
$('a.mylink')[0].click()
최근 jQuery를 통해 마우스 클릭 이벤트를 트리거하는 방법을 찾았습니다.
<script type="text/javascript">
var a = $('.path > .to > .element > a')[0];
var e = document.createEvent('MouseEvents');
e.initEvent( 'click', true, true );
a.dispatchEvent(e);
</script>
이 접근법은 파이어 폭스, 크롬 및 IE에서 작동합니다. 그것이 누군가를 돕기를 바랍니다.
var comp = document.getElementById('yourCompId');
try { //in firefox
comp.click();
return;
} catch(ex) {}
try { // in chrome
if(document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent( 'click', true, true );
comp.dispatchEvent(e);
return;
}
} catch(ex) {}
try { // in IE
if(document.createEventObject) {
var evObj = document.createEventObject();
comp.fireEvent("onclick", evObj);
return;
}
} catch(ex) {}
이것은 매우 오래된 질문이지만이 작업을 처리하기가 더 쉽다는 것을 알았습니다. 그것은 jquery UI 팀이 개발 한 jquery 플러그인입니다. jquery 뒤에 포함시킬 수 있으며 다음과 같은 작업을 수행 할 수 있습니다
<a href="http://stackoverflow.com/"></a>
$('a').simulate('click');
크롬, 파이어 폭스, 오페라 및 IE10에서 잘 작동합니다. https://github.com/eduardolundgren/jquery-simulate/blob/master/jquery.simulate.js 에서 다운로드 할 수 있습니다
The question title says "How can I simulate an anchor click in jQuery?". Well, you can use the "trigger" or "triggerHandler" methods, like so:
<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript" src="path/to/thickbox.js"></script>
<script type="text/javascript">
$(function() {
$('#btn').click(function() {
$('#thickboxId').triggerHandler('click');
})
})
</script>
...
<input id="btn" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
Not tested, this actual script, but I've used trigger
et al before, and they worked a'ight.
UPDATE
triggerHandler
doesn't actually do what the OP wants. I think 1421968 provides the best answer to this question.
I'd suggest to look at the Selenium API to see how they trigger a click on an element in a browser-compatible manner:
Look for the BrowserBot.prototype.triggerMouseEvent
function.
I believe you can use:
$('#yourLink').bind('click', function() {
//Do something over here
});
$('#yourLink').trigger('click');
This will easily trigger the click function, without actually clicking on it.
Do you need to fake an anchor click? From the thickbox site:
ThickBox can be invoked from a link element, input element (typically a button), and the area element (image maps).
If that is acceptable it should be as easy as putting the thickbox class on the input itself:
<input id="thickboxButton" type="button" class="thickbox" value="Click me">
If not, I would recommend using Firebug and placing a breakpoint in the onclick method of the anchor element to see if it's only triggered on the first click.
Edit:
Okay, I had to try it for myself and for me pretty much exactly your code worked in both Chrome and Firefox:
<html>
<head>
<link rel="stylesheet" href="thickbox.css" type="text/css" media="screen" />
</head>
<body>
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="thickbox.js" type="text/javascript"></script>
<input onclick="$('#thickboxId').click();" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
</body>
</html>
The window pop ups no matter if I click the input or the anchor element. If the above code works for you, I suggest your error lies elsewhere and that you try to isolate the problem.
Another possibly is that we are using different versions of jquery/thickbox. I am using what I got from the thickbox page - jquery 1.3.2 and thickbox 3.1.
You can create a form via jQuery or in the HTML page code with an action that mimics your link href:
<a id="anchor_link" href="somepath.php">click here</a>.
var link = $('#anchor_link').attr('href');
$('body').append('<form id="new_form" action="'+link+'"></form>');
$('#new_form').submit();
To simulate a click on an anchor while landing on a page, I just used jQuery to animate the scrollTop property in $(document).ready.
No need for a complex trigger, and that works on IE 6 and every other browser.
If you don't need to use JQuery, as I don't. I've had problems with the cross browser func of .click()
. So I use:
eval(document.getElementById('someid').href)
In Javascript you can do like this
function submitRequest(buttonId) {
if (document.getElementById(buttonId) == null
|| document.getElementById(buttonId) == undefined) {
return;
}
if (document.getElementById(buttonId).dispatchEvent) {
var e = document.createEvent("MouseEvents");
e.initEvent("click", true, true);
document.getElementById(buttonId).dispatchEvent(e);
} else {
document.getElementById(buttonId).click();
}
}
and you can use it like
submitRequest("target-element-id");
Using Jure's script I made this, to easily "click" as many elements as you want.
I just used it Google Reader on 1600+ items and it worked perfectly (in Firefox)!
var e = document.createEvent('MouseEvents');
e.initEvent( 'click', true, true );
$(selector).each(function(){this.dispatchEvent(e);});
JQuery('#left').triggerHandler('click');
works fine in Firefox and IE7. I haven't tested it on other browsers.
If want to trigger automatic user clicks do the following:
window.setInterval(function()
{
$('#left').triggerHandler('click');
}, 1000);
This doesn't work on android native browser to click "hidden input (file) element":
$('a#swaswararedirectlink')[0].click();
But this works:
$("#input-file").show();
$("#input-file")[0].click();
$("#input-file").hide();
In trying to simulate a 'click' in unit tests with the jQuery UI spinner I could not get any of the previous answers to work. In particular, I was trying to simulate the 'spin' of selecting the down arrow. I looked at the jQuery UI spinner unit tests and they use the following method, which worked for me:
element.spinner( "widget" ).find( ".ui-spinner-up" ).mousedown().mouseup();
참고URL : https://stackoverflow.com/questions/773639/how-can-i-simulate-an-anchor-click-via-jquery
'Programing' 카테고리의 다른 글
숭고한 텍스트 2 여러 줄 편집 (0) | 2020.06.16 |
---|---|
신속한 사건 (0) | 2020.06.16 |
공분산과 역 분산의 차이 (0) | 2020.06.16 |
Chrome 콘솔에서 전체 개체를 표시하는 방법은 무엇입니까? (0) | 2020.06.16 |
Laravel 5 이메일을 사용하려고합니다 (0) | 2020.06.15 |