1

I have a problem with the variables, that I want to pass through ajax to php.

In an php file, I generate some divs with id and name attributes.

livesrc.php

echo "<div class=\"search-results\" id=\"" . $softwareArray['Sw_idn'] . "\" 
name=\"" . $softwareArray['SoftwareName'] . "\" 
onclick=\"addBasket(this.id, this.name)\" >
" . utf8_encode($softwareArray['SoftwareName']) . "</div>";

The relevent part is this:

onclick="addBasket(this.id, this.name)

Sorry for the escapes, in html the div looks like:

<div class="search-results" id="235" 
name="Adobe Acrobat Writer 9.0 Professional"
onclick="addBasket(this.id, this.name)">...</div>

This looks okay, but in the js "addBasket", the variable sw_name is not set. (undefinded)

The JS in the head section:

<script type="text/javascript">
  function addBasket(sw_id, sw_name) 
  {
    alert(sw_name);
    $.post("assets/basket.php",{sw_id: sw_id, sw_name: sw_name}, function(data) 
  { 
      $("#basket").html(data);
    });
  }
</script>

The sw_id is set, but the sw_name is not working. Is the call in html with "this.name" correct?

4

2 回答 2

5

这是因为this.name如果你想访问你必须调用的属性this.getAttribute('name')id 是特定的并且可以直接访问,所以不存在。

就我个人而言,我将把它交给函数并在函数中提取 id 和 name

 onclick="addBasket(this)";




<script type="text/javascript">
  function addBasket(el) 
  {
    var 
    sw_id = el.id,
    sw_name = $(el).attr('name');

    alert(sw_name);
    $.post("assets/basket.php",{sw_id: sw_id, sw_name: sw_name}, function(data) 
  { 
      $("#basket").html(data);
    });
  }
</script>
于 2013-10-14T15:49:27.943 回答
0

您可以将整个元素传递到您的 js 中:

<div class="search-results" id="235" 
name="Adobe Acrobat Writer 9.0 Professional"
onclick="addBasket(this)">...</div>

然后在你的函数中获取你想要的

function addBasket(sw) {
    alert( sw.id + ' ' + sw.getAttribute( 'name' ) );
}
于 2013-10-14T15:53:15.780 回答