显示两个复选框元素的标题之间的数学差异

Display the mathematical difference between the title of 2 checkbox elements

本文关键字:之间 标题 元素 复选框 两个 显示      更新时间:2023-09-26

我有一个表单,它使用与下面的复选框类似的复选框

<Form>
 <table>
    <tr>
      <td align="left" width="15"><input name="switch" title="0" id="radio17" value="Free Shipping" checked="checked" type="radio" />
      </td>
      <td>Free Shipping</td>
    </tr>
    <tr>
      <td align="left" width="15"><input name="switch" title="38" id="radio18" value="Standard Shipping" type="radio" />
      </td>
      <td>Standard Shipping
      </td>
    </tr>
</table>

我需要的是价格的差异,它由标题表示,显示在名称旁边。因此,如果选择了免费送货,输出应该看起来像"免费送货[+0]",标准送货看起来像"标准送货[+38]"

我只是在学习javascript,所以这将是首选,但如果它有效,任何事情都可以。

你的意思是这样的吗?

<form> 
  <label><input type="radio" name="switch" title="Free Shipping" id="freeshipping" value="0" checked="checked" type="radio" />Free Shipping</label>    
  <label><input type="radio" name="switch" title="Standard Shipping" id="standardshipping" value="38" />Standard Shipping</label>
  <div>Selected shipping method: <span id="shippingtitle"> </span> [+<span id="shippingcost"> </span>]</div> 
</form>
window.onload = function(){
    var i;
    for(i = 0; i < document.getElementsByName('switch').length; ++i){
        document.getElementsByName('switch')[i].onclick = function(){
            document.getElementById('shippingtitle').firstChild.data = this.title;
            document.getElementById('shippingcost').firstChild.data = this.value;
        }
    }
};

label{
    display:block;
    float:left;
    clear:left;
    width:30%;
}
form{
    max-width:500px;
}

你似乎只是在学习JavaScript。这很好,但如果你想驾驶汽车,就不要使用直升机(在使用jQuery之前,学习基本的JavaScript并阅读一点DOM)。

我将通过id访问单选元素,然后更新其父元素的同级元素的文本,以包含单选按钮的"title"属性的值。例如:

function showPriceDifference(id) {
  var el = document.getElementById(id)
    , price = el.getAttribute('title');
  el.parentElement.nextElementSibling.innerHTML += ' [+' + price + ']';
}
showPriceDifference('radio17');
showPriceDifference('radio18');