簡體   English   中英

document.getElementById()問題

[英]document.getElementById() problem

我有這行代碼:

<a href="#" id="profilelink" name="profilelink" 
    value="<?php echo $id."/".$block_record;?>" 
    onClick="return viewornot(<?php echo $id; ?>)">
   <?php echo $uniqueCode; ?>
</a>

因此,使用onclick時,我想將與被阻止的ID串聯在一起的ID傳遞給我的JS:

function viewornot()
{
    var val = document.getElementById('profilelink');
    var e = confirm('Do you want to view this profile?');

    if (e == true)
    { 
       //for live site
       window.location.href = "http://www.rainbowcode.net/index.php/profiles/showprofilepersonal?id="+id;
       return true;
    }
    else
    {
        //if val contains a 1 then user is blocked
        //display a message then
    }
    return false
}      

該行: var val = document.getElementById('profilelink'); 沒有給我我想要的內容,它應該包含與1(已阻止)或0(未阻止) ($id."/".$blocked_user)連接的用戶ID

有人能幫助我嗎? 謝謝

document.getElementById('profilelink')返回對DOM的引用,而不是您指定的value屬性( 這是無效的HTML )。

將其更改為 document.getElementById('profilelink').value 在兼容的瀏覽器中可能會失敗,因為value不是標記的有效屬性

要么

document.getElementById('profilelink').getAttribute('value');

演示在 http://jsfiddle.net/gaby/EWdLD/


另外 ,您很可能希望將viewornot()定義更改為viewornot(id)因為您似乎將其作為參數傳遞,並在方法內部使用它。


在安全方面 ,我希望您不要將其用於真正的安全,因為通過在客戶端中操作DOM可以輕松繞過它。 為了獲得更強大的安全性,請使用一些服務器端代碼對每個請求進行阻止/取消阻止。

沒有指出明顯的地方,但是val不是實際值。 您需要document.getElementById('profilelink').value來做到這一點。

當你做

var val = document.getElementById('profilelink');

您實際上正在使用作為鏈接的DOM元素。 您真正想要的是傳遞給您的方法的參數。

更改您的方法簽名

function viewornot(blockedStatus) {
   var val = blockedStatus;
   //your code
}

您可能還想更改鏈接

<a href="#" id="profilelink" name="profilelink" 
    value="<?php echo $id."/".$block_record;?>" 
  -->   onClick="return viewornot('<?php echo $id."/".$block_record;?>')">
   <?php echo $uniqueCode; ?>
</a>

a標簽沒有value屬性。 您需要將此值傳遞給函數。

<a href="#" id="profilelink" name="profilelink" onClick="return viewornot(<?php echo $block_record; ?>)"><?php echo $uniqueCode; ?></a>

<a>標記中沒有可用的"value"屬性,您可以將其作為參數傳遞,並將另一個參數作為傳遞

例如:

<a onclick="view(<?php echo id ?>)</a>

<script>
   function view(id){
         alert(id);
   }
</script>

試試這個

如果要循環鏈接創建腳本,則每個鏈接將具有一個profilelink的ID。 您可以通過將數據庫ID添加到錨標記中ID的末尾來解決此問題。 最好將所有內容都傳遞給該函數,而不用擔心為錨定變量。

Ahref不能有值。 只需通過onclick函數傳遞“ val”即可。 “ val”將通過函數傳遞,然后您不需要getElementById

<a href="#" id="profilelink" name="profilelink" onClick="viewornot(<?php echo $id; ?>)"><?php echo $uniqueCode; ?></a>

    function viewornot(val)
    {

    var e = confirm('Do you want to view this profile?');

    if (e == true)
    { 
       //for live site
       window.location.href = "http://www.rainbowcode.net/index.php/profiles/showprofilepersonal?id="+id;
       return true;
    }
    else
    {
        //if val contains a 1 then user is blocked
        //display a message then
    }
    return false
}      

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM