button 누르면 iframe 으로 전송하기

button 누르면 iframe 으로 전송하기

QA

button 누르면 iframe 으로 전송하기

본문

아래와 같이 버튼을 누르면  iframe 에서 페이지가 열리게 하려고 합니다.

버튼을 누르면 2개 iframe 에서 모두 작동하는 문제가 있네요.

무엇이 잘못된걸까요?

 

<button type="button" class="btn hz-btn-icon sleep" onclick="postYourAdd1">네이버</button>
<button type="button" class="btn hz-btn-icon screenon" onclick="postYourAdd2">다음</button>

 

<iframe id="forPostyouradd1" data-src="https://naver.com" 
    src="about:blank" width="200" height="100" style="background-color:coral">
</iframe>
<iframe id="forPostyouradd2" data-src="https://daum.net" 
    src="about:blank" width="200" height="100" style="background-color:aqua">
</iframe>


<script>
    function postYourAdd1() {
        var iframe = $("#forPostyouradd1");
        iframe.attr("src", iframe.data("src")); 
    }
    $("button").on("click", postYourAdd1);
</script>
<script>
    function postYourAdd2() {
        var iframe = $("#forPostyouradd2");
        iframe.attr("src", iframe.data("src")); 
    }
    $("button").on("click", postYourAdd2);
</script>

이 질문에 댓글 쓰기 :

답변 3

button 의 onclick 을 삭제하고

script 에서 button 을 구분해서 이벤트 핸들러를 등록하는 방법입니다.

 


<button type="button" class="btn hz-btn-icon sleep">네이버</button>
<button type="button" class="btn hz-btn-icon screenon">다음</button>
 
<iframe id="forPostyouradd1" data-src="https://naver.com" 
    src="about:blank" width="200" height="100" style="background-color:coral">
</iframe>
<iframe id="forPostyouradd2" data-src="https://daum.net" 
    src="about:blank" width="200" height="100" style="background-color:aqua">
</iframe>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    function postYourAdd1() {
        var iframe = $("#forPostyouradd1");
        iframe.attr("src", iframe.data("src")); 
    }
    $("button.sleep").on("click", postYourAdd1);
</script>
<script>
    function postYourAdd2() {
        var iframe = $("#forPostyouradd2");
        iframe.attr("src", iframe.data("src")); 
    }
    $("button.screenon").on("click", postYourAdd2);
</script>

 $("button").on("click", postYourAdd1);

은 모든 버튼 태그에 해당됩니다.

ID 를 지정하여 ID 셀렉터를 사용하는 것이 적절해 보입니다.

<button id="btn1" ~

$("#btn1").on("click", postYourAdd1);

답변을 작성하시기 전에 로그인 해주세요.
전체 671
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT